簡體   English   中英

C ++通過分隔符拆分字符串並保持結果中的分隔符

[英]C++ spliting string by delimiters and keeping the delimiters in result

我正在尋找一種方法,使用C ++中的正則表達式分隔多個分隔符的字符串,但不會丟失輸出中的分隔符,保持分隔符的順序分隔符,例如:

輸入

AAA,bbb.ccc,DDD-EEE;

產量

aaa,bbb。 ccc,ddd - eee;

我已經找到了一些解決方案,但都是在C#或java中,尋找一些C ++解決方案,最好不使用Boost。

您可以在regex_iterator的示例之上構建解決方案。 例如,如果您知道分隔符是逗號,句點,分號和連字符,則可以使用捕獲分隔符或一系列非分隔符的正則表達式:

([.,;-]|[^.,;-]+)

將其放入示例代碼中,最終得到如下內容

#include <iostream>
#include <string>
#include <regex>

int main ()
{
  // the following two lines are edited; the remainder are directly from the reference.
  std::string s ("aaa,bbb.ccc,ddd-eee;");
  std::regex e ("([.,;-]|[^.,;-]+)");   // matches delimiters or consecutive non-delimiters

  std::regex_iterator<std::string::iterator> rit ( s.begin(), s.end(), e );
  std::regex_iterator<std::string::iterator> rend;

  while (rit!=rend) {
    std::cout << rit->str() << std::endl;
    ++rit;
  }

  return 0;
}

嘗試替換您喜歡的任何其他正則表達式。

對於您的情況,根據單詞boundary \\b拆分輸入字符串,除了第一個輸出字符串將為您提供所需的輸出。

(?!^)\b

DEMO

要么

(?<=\W)(?!$)|(?!^)(?=\W)

DEMO

  • (?<=\\W)(?!$)匹配非單詞字符旁邊的邊界,但不匹配最后出現的邊界。

  • | 要么

  • (?!^)(?=\\W)匹配除了開頭的字符之外的非字字符的邊界。

如有必要,再次逃避反斜杠。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM