gpt4 book ai didi

c++ - 如何将多个替代模式之一与 C++11 正则表达式匹配

转载 作者:太空狗 更新时间:2023-10-29 21:18:08 25 4
gpt4 key购买 nike

<分区>

使用 Perl,匹配结果如下:

echo xyz | perl -ne 'print if (/.*(yes|no|xy).*/);'

我正在尝试使用 C++ 正则表达式实现相同的目的。 ECMAScript syntax documentation

A regular expression can contain multiple alternative patterns simply by separating them with the separator operator (|): The regular expression will match if any of the alternatives match, and as soon as one does.

但是,以下示例似乎表明 std::regex_match 仅匹配前两个备选方案,而忽略第三个备选方案:

std::string pattern1 = ".*(yes|no|xy).*";
std::string pattern2 = ".*(yes|xy|no).*";
std::regex re1(pattern1);
std::regex re2(pattern2);
for (std::string str : {"yesplease", "bayes", "nobody", "anode", "xyz", "abc"} ) {
if (std::regex_match(str,re1)) {
std::cout << str << "\t\tmatches " << pattern1 << "\n";
}
else if (std::regex_match(str,re2)) {
std::cout << str << "\t\tmatches " << pattern2 << "\n";
}
}

输出:

yesplease   matches .*(yes|no|xy).*
bayes matches .*(yes|no|xy).*
nobody matches .*(yes|no|xy).*
anode matches .*(yes|no|xy).*
xyz matches .*(yes|xy|no).*

如何获得与我的 Perl 正则表达式示例相同的行为,即让“xyz”匹配模式 1?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com