除非逗号在括号内,否则逗号分隔的正则表达式

3

我需要将这样的字符串分隔开:

猫,狗,蚂蚁(大象,狮子(老虎)),鸟

变成这样:

cat
dog
ant( elephant, lion(tiger))
bird

我的当前状态是这样的:(\w+)(,\s*)*,但这也会将大象、狮子和老虎分开。此外,一些逗号和空格被保留。

你可能已经猜到,在进一步的迭代中我将在ant(...)字符串上再次调用相同的表达式。如果需要的话,我将在c ++中使用它。


1
这似乎不是一种常规语言。你需要更强大的解析器。 - Kerrek SB
1
可能相当于https://dev59.com/X3I-5IYBdhLWcg3wq6do。 - Kerrek SB
1
不确定正则表达式是否是正确的方法,但你可以使用一个非常简单的C/C++解析函数来完成这个任务。 - 16tons
1个回答

3

This regex:

(\w+\(.+\))|\w+

将解析
cat, dog , ant( elephant, lion(tiger)), bird

Into:

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';
}

在线演示


谢谢你的回答,明天会测试一下。string/regex 前面的 R 有什么作用? - dani
@dani 这是一个原始字符串字面值,它使得编写正则表达式字符串时无需转义所有斜杠成为可能。 - wally

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接