这是代码:
#include <string>
#include <regex>
#include <iostream>
int main()
{
std::string pattern("[^c]ei");
pattern = "[[:alpha:]]*" + pattern + "[[:alpha:]]*";
std::regex r(pattern);
std::smatch results;
std::string test_str = "cei";
if (std::regex_search(test_str, results, r))
std::cout << results.str() << std::endl;
return 0;
}
输出 :
cei
使用的编译器是gcc 4.9.1
。
我是一个学习正则表达式的新手。我希望什么都不会输出,因为"cei"
这里的模式不匹配。我做对了吗?有什么问题?
更新:
已报告并确认此错误为错误,有关详细信息,请访问此处:https : //gcc.gnu.org/bugzilla/show_bug.cgi?id=63497
这是实现中的错误。我尝试过的其他几个工具不仅同意您的模式与您的输入不匹配,而且还尝试了以下方法:
#include <string>
#include <regex>
#include <iostream>
int main()
{
std::string pattern("([a-z]*)([a-z])(e)(i)([a-z]*)");
std::regex r(pattern);
std::smatch results;
std::string test_str = "cei";
if (std::regex_search(test_str, results, r))
{
std::cout << results.str() << std::endl;
for (size_t i = 0; i < results.size(); ++i) {
std::ssub_match sub_match = results[i];
std::string sub_match_str = sub_match.str();
std::cout << i << ": " << sub_match_str << '\n';
}
}
}
这基本上与您所拥有的相似,但是为了简单起见,我用替换[:alpha:]
了它[a-z]
,并且我暂时也替换[^c]
了[a-z]
它,因为这似乎使其正常工作。打印内容如下(Linux x86-64上的GCC 4.9.0):
cei
0: cei
1:
2: c
3: e
4: i
5:
如果我替换了[a-z]
原来的位置,[^c]
而只是放在f
那里,它正确地表示该模式不匹配。但是,如果我[^c]
像您一样使用:
std::string pattern("([a-z]*)([^c])(e)(i)([a-z]*)");
然后我得到以下输出:
cei
0: cei
1: cei
terminate called after throwing an instance of 'std::length_error'
what(): basic_string::_S_create
Aborted (core dumped)
因此,它声称匹配成功,并且result [0]是预期的“ cei”。然后,结果[1]也是“ cei”,我想可能还可以。但是结果[2]崩溃了,因为它试图用begin = nullptr构造一个std::string
长度为a的长度18446744073709551614
。这个巨大的数字2^64 - 2
就是std::string::npos - 1
(在我的系统上)。
因此,我认为某个地方存在一个错误的错误,其影响可能不仅仅是伪造的正则表达式匹配-它可能在运行时崩溃。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句