C通过分隔符分割字符串并保持分隔符的结果
发布时间:2020-12-16 10:35:19 所属栏目:百科 来源:网络整理
导读:我正在寻找一种方法,使用C中的正则表达式分割多个分隔符的字符串但不丢失输出中的分隔符,保持分隔符的顺序分隔符,例如: 输入 aaa,bbb.ccc,ddd-eee; 产量 aaa,bbb . ccc,ddd – eee ; 我已经找到了一些解决方案,但都在C#或java中,寻找一些C解决方案,最好不使
我正在寻找一种方法,使用C中的正则表达式分割多个分隔符的字符串但不丢失输出中的分隔符,保持分隔符的顺序分隔符,例如:
输入
产量
我已经找到了一些解决方案,但都在C#或java中,寻找一些C解决方案,最好不使用Boost. 解决方法
您可以在
regex_iterator 的示例之上构建解决方案.例如,如果您知道分隔符是逗号,句点,分号和连字符,则可以使用捕获分隔符或一系列非分隔符的正则表达式:
([.,;-]|[^.,;-]+) 将其放入示例代码中,最终得到something like this: #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,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; } 尝试替换您喜欢的任何其他正则表达式. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |