c++ - 正则表达式搜索文本然后匹配元素

标签 c++ regex regex-group

我想安装一个条件。我已经尝试了很多但没有成功。会有人这么好心帮我吗?

我的目标:如果 SharedKeys 为真则匹配元素 (A B C D)。

SharedKeys = "A","B","C","D"

正则表达式:(?!\")[A-Z]*?(?=\")

匹配元素:A B C D

更新:(SharedKeys)?(?(1)|(?!\")[A-Z]*?(?=\"))

匹配元素:SharedKeys A B C D

链接:https://regex101.com/r/WFxZh4/1

我想我现在已经拥有了我需要的东西,也许可以帮助其他人。

SharedKeys = "A","B","C","D"

BlaBla = "B", "B", "C"

结果:(SharedKeys|BlaBla)?(?(1)|(?!\")[A-Z]*?(?=\"))

匹配元素:SharedKeys A B C D BlaBla B B C

C++ 的结果:[A-Za-z]+|(?!\")[A-Z]*?(?=\") (std::regex)

最佳答案

使用std::regex:

std::string s1( R"(SharedKeys = "A","B","C","D")" );
std::regex rx( "(SharedKeys)?(?(1)|[A-Z](?=\\\"))" );
std::match_results< std::string::const_iterator > mr;

while( std::regex_search( s1, mr, rx ) ){
    std::cout << mr.str() << '\n';
    s1 = mr.suffix().str();
}

输出:

terminate called after throwing an instance of 'std::regex_error'  
what():  Invalid special open parenthesis. Aborted (core dumped)

使用boost::regex:

std::string s1( R"(SharedKeys = "A","B","C","D")" );
boost::regex rx( "(SharedKeys)?(?(1)|[A-Z](?=\\\"))" );
boost::match_results< std::string::const_iterator > mr;

while( boost::regex_search( s1, mr, rx ) ){
    std::cout << mr.str() << '\n';
    s1 = mr.suffix().str();
}

输出:

SharedKeys
A
B
C
D

在这里你可以看到这两种口味的区别:

boost_regex_table

source of the screenshot


注意。 std::regex 有问题,尤其是 gcc version 6.3.0 and lower versions

关于c++ - 正则表达式搜索文本然后匹配元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44909227/

相关文章:

python - Boost不将模块暴露给python

c++ - 为类型分配唯一的整数标识符,编译时

c++ - 使用 QtCreator(qmake) 编译 wtwithqt 示例

regex - 使用正则表达式来匹配字符串的变体

正则表达式约束验证-grails

regex - Notepad++正则表达式替换命名组

c++ - 一条关于如何实现字符串和长整数、整数、 double 模板函数的建议

java - 帮助清理 Java 中的 Code-39 条形码数据

python - 使用组标签 ?P<> 正则表达式到字典

java - 正则表达式 - 捕获条件组