gpt4 book ai didi

c++ - 在 libc++ 上,为什么 regex_match ("tournament", regex ("tour|to|tournament")) 失败?

转载 作者:可可西里 更新时间:2023-11-01 17:56:11 26 4
gpt4 key购买 nike

http://llvm.org/svn/llvm-project/libcxx/trunk/test/re/re.alg/re.alg.match/ecma.pass.cpp ,存在以下测试:

    std::cmatch m;
const char s[] = "tournament";
assert(!std::regex_match(s, m, std::regex("tour|to|tournament")));
assert(m.size() == 0);

为什么这个匹配会失败?

在VC++2012和boost上,匹配成功。
在 Chrome 和 Firefox 的 Javascript 上,"tournament".match(/^(?:tour|to|tournament)$/) 成功。

仅在 libc++ 上,匹配失败。

最佳答案

我相信测试是正确的。在 re.alg 下的所有 libc++ 测试中搜索“tournament”并比较不同引擎如何处理 regex("tour|to|tournament") 是有益的。 ,以及如何regex_search不同于 regex_match .

让我们从regex_search开始:

awk,egrep,扩展:

regex_search("tournament", m, regex("tour|to|tournament"))

matches the entire input string: "tournament".

ECMAScript:

regex_search("tournament", m, regex("tour|to|tournament"))

matches only part of the input string: "tour".

grep,基本的:

regex_search("tournament", m, regex("tour|to|tournament"))

Doesn't match at all. The '|' character is not special.

awk、egrep 和 extended 将尽可能多地匹配交替。然而,ECMAScript 交替是“有序的”。这在 ECMA-262 中指定.一旦 ECMAScript 匹配了交替中的一个分支,它就会退出搜索。该标准包括这个例子:

/a|ab/.exec("abc")

returns the result "a" and not "ab".

<plug>

这也在 Mastering Regular Expressions by Jeffrey E.F. Friedl 中进行了深入讨论。 .我无法实现 <regex>没有这本书。我坦率地承认,关于正则表达式,我不知道的比我知道的要多得多。

在交替章节的结尾,作者指出:

If you understood everything in this chapter the first time you read it, you probably didn't read it in the first place.

相信吧!

</plug>

无论如何,ECMAScript 只匹配“tour”。 regex_match仅当匹配整个 输入字符串时,算法才会返回成功。由于仅匹配输入字符串的前 4 个字符,因此与 awk、egrep 和扩展不同,ECMAScript 返回 false 并返回大小为零的 cmatch。 .

关于c++ - 在 libc++ 上,为什么 regex_match ("tournament", regex ("tour|to|tournament")) 失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17609325/

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