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

标签 c++ regex

我需要像这样分隔一个字符串:

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

进入这个:

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

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

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

最佳答案

This regex :

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

live demo

关于c++ - 逗号分隔的正则表达式,除非逗号在括号内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41663467/

相关文章:

c++ - C++段错误中的命令行参数

c++ - 如何检查模板的参数类型是否完整?

regex - Vim:如何只搜索和替换每一行的一部分?

MySQL,REGEXP - 查找仅包含以下确切字母的单词

Python正则表达式获取特定字符串后的第一个元素

使用方法声明 "_Something"在 VBA(Excel) 中导入 C++ dll

c++ - 在 C++ 中的函数内更改二维数组的值

c++ - TCP 套接字 : detect if peer has shut down before sending? (Linux)

regex - 为什么 New-AzureRmVM 给出实体名称错误?

python - 用于匹配两个字符之间的文本同时忽略反斜杠字符的正则表达式