gpt4 book ai didi

c++ - std::regex_match 和具有奇怪行为的惰性量词

转载 作者:行者123 更新时间:2023-11-28 05:17:03 30 4
gpt4 key购买 nike

我知道:
惰性量词匹配:尽可能少(最短匹配)

还知道构造函数:

basic_regex( ...,
flag_type f = std::regex_constants::ECMAScript );

并且:
ECMAScript支持非贪婪匹配,
ECMAScript正则表达式 "<tag[^>]*>.*?</tag>"
只会匹配到 first 结束标记 ... en.cppreference

并且:
最多必须从 ECMAScript 中选择一个语法选项, basic , extended , awk , grep , egrep .如果没有选择语法, ECMAScript假设选择... en.cppreference

并且:
注意 regex_match只会成功地将正则表达式匹配到整个字符序列,而 std::regex_search将成功匹配子序列... std::regex_match


这是我的代码:+ Live

#include <iostream>
#include <string>
#include <regex>

int main(){

std::string string( "s/one/two/three/four/five/six/g" );
std::match_results< std::string::const_iterator > match;
std::basic_regex< char > regex ( "s?/.+?/g?" ); // non-greedy
bool test = false;

using namespace std::regex_constants;

// okay recognize the lazy operator .+?
test = std::regex_search( string, match, regex );
std::cout << test << '\n';
std::cout << match.str() << '\n';
// does not recognize the lazy operator .+?
test = std::regex_match( string, match, regex, match_not_bol | match_not_eol );
std::cout << test << '\n';
std::cout << match.str() << '\n';
}

和输出:

1
s/one/
1
s/one/two/three/four/five/six/g

Process returned 0 (0x0) execution time : 0.008 s
Press ENTER to continue.

std::regex_match不应该匹配任何东西,它应该返回 0带有非贪婪量词.+?

其实这里,非贪婪 .+?量词与greedy 含义相同,两者都是/.+?//.+/匹配相同的字符串。它们是不同的图案。那么问题是为什么忽略了问号?

regex101

快速测试:

$ echo 's/one/two/three/four/five/six/g' | perl -lne '/s?\/.+?\/g?/ && print $&'
$ s/one/
$
$ echo 's/one/two/three/four/five/six/g' | perl -lne '/s?\/.+\/g?/ && print $&'
$ s/one/two/three/four/five/six/g

注意
这个正则表达式:std::basic_regex< char > regex ( "s?/.+?/g?" );非贪婪
还有这个:std::basic_regex< char > regex ( "s?/.+/g?" );贪心
std::regex_match 具有相同的输出.仍然都匹配整个字符串!
但是用std::regex_search有不同的输出。
还有 s?g?没关系和/.*?/仍然匹配整个字符串!

更多细节

g++ --version
g++ (Ubuntu 6.2.0-3ubuntu11~16.04) 6.2.0 20160901

最佳答案

我没有看到任何不一致。 regex_match 尝试匹配整个字符串,因此 s?/.+?/g? 延迟扩展直到覆盖整个字符串。

这些“图表”(用于 regex_search)有望帮助理解贪心:

Non-greedy:

a.*?a: ababa
a|.*?a: a|baba
a.*?|a: a|baba # ok, let's try .*? == "" first
# can't go further, backtracking
a.*?|a: ab|aba # lets try .*? == "b" now
a.*?a|: aba|ba
# If the regex were a.*?a$, there would be two extra backtracking
# steps such that .*? == "bab".

Greedy:

a.*?a: ababa
a|.*a: a|baba
a.*|a: ababa| # try .* == "baba" first
# backtrack
a.*|a: abab|a # try .* == "bab" now
a.*a|: ababa|

在这种情况下,regex_match( abc ) 类似于 regex_search( ^abc$ )

关于c++ - std::regex_match 和具有奇怪行为的惰性量词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42422778/

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