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

时间:2017-07-04 15:01:21

标签: c++ regex regex-group

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

我的目标:如果SharedKeys为true,则匹配元素(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)

1 个答案:

答案 0 :(得分:1)

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