我需要这样的字符串:
cat, dog , ant( elephant, lion(tiger)), bird
到这个:
cat
dog
ant( elephant, lion(tiger))
bird
我目前的状态是:(\w+)(,\s*)*
,但也将大象,狮子和老虎分开。此外,保留了一些逗号和空格。
您可能已经猜到,ant(...)
在进一步的迭代中,我将再次在字符串上调用相同的表达式。如果重要的话,我将在c ++中使用它。
(\w+\(.+\))|\w+
将解析
cat, dog , ant( elephant, lion(tiger)), bird
进入:
cat
dog
ant( elephant, lion(tiger))
bird
完整程序:
#include <string>
#include <vector>
#include <iterator>
#include <regex>
#include <iostream>
int main()
{
std::string str{R"(cat, dog , ant( elephant, lion(tiger)), bird)"};
std::regex r{R"((\w+\(.+\))|\w+)"};
std::vector<std::string> result{};
auto it = std::sregex_iterator(str.begin(), str.end(), r);
auto end = std::sregex_iterator();
for(; it != end; ++it) {
auto match = *it;
result.push_back(match[0].str());
}
std::cout << "Input string: " << str << '\n';
std::cout << "Result:\n";
for(auto i : result)
std::cout << i << '\n';
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句