![](/img/trans.png)
[英]split a string using multiple delimiters (including delimiters) in 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;
}
嘗試替換您喜歡的任何其他正則表達式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.