Regex不匹配,除非整行都相同

Regex not matching unless the entire line is the same

本文关键字:不匹配 Regex      更新时间:2023-10-16

我的regex有问题。例如,在以下代码中,if语句返回false:

string test("ABC123");
regex e("123");
if(regex_match (test.begin(), test.end(), e))
{
//do something
}

使正则表达式返回true的唯一方法是将正则表达式设置为"ABC123"".+"。其他可能的正则表达式,如"[0-9]""[A-Z]"也返回false。

否,请参阅以下解释:

整个目标序列必须与此的正则表达式匹配函数返回true(即,没有任何附加字符在比赛之前或之后)。对于当匹配只是序列的一部分,请参见regex_search。

请改用regex_search

返回true:

string test("ABC123");
regex e("123");
if(regex_search (test.begin(), test.end(), e))
{
return true;
}

您应该使用

regex_search(test.begin(), test.end(), e))

而是

只有当测试的整个字符串与regex匹配时,regex_match才会返回true。否则,如果字符串中的子字符串与您的匹配,regex_search将返回true。

请查看此链接了解更多信息:

http://www.johndcook.com/blog/cpp_regex/