逗号分隔的正则表达式,除非逗号在括号内
Regular expression for comma-separation except if the comma is within parenthesis
我需要像这样分隔字符串:
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';
}
我需要像这样分隔字符串:
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';
}