我想安装一个条件。我已经尝试了很多但没有成功。会有人这么好心帮我吗?
我的目标:如果 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
在这里你可以看到这两种口味的区别:
注意。 std::regex
有问题,尤其是 gcc version 6.3.0
and lower versions
关于c++ - 正则表达式搜索文本然后匹配元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44909227/