std::regex_match 和 std::regex_search 之间的区别?
Difference between std::regex_match & std::regex_search?
下面的程序已被编写为使用C++11 std::regex_match & std::regex_search获取"Day"信息。但是,使用第一种方法返回false
,第二种方法返回true
(预期(。我阅读了与此相关的文档和已经存在的 SO 问题,但我不明白这两种方法之间的区别以及我们何时应该使用其中任何一种? 它们可以互换用于任何常见问题吗?
regex_match和regex_search的区别?
#include<iostream>
#include<string>
#include<regex>
int main()
{
std::string input{ "Mon Nov 25 20:54:36 2013" };
//Day:: Exactly Two Number surrounded by spaces in both side
std::regex r{R"(sd{2}s)"};
//std::regex r{"\s\d{2}\s"};
std::smatch match;
if (std::regex_match(input,match,r)) {
std::cout << "Found" << "n";
} else {
std::cout << "Did Not Found" << "n";
}
if (std::regex_search(input, match,r)) {
std::cout << "Found" << "n";
if (match.ready()){
std::string out = match[0];
std::cout << out << "n";
}
}
else {
std::cout << "Did Not Found" << "n";
}
}
输出
Did Not Found
Found
25
为什么在这种情况下,第一个正则表达式方法返回false
?regex
似乎是正确的,因此理想情况下两者都应该返回true
。我通过将std::regex_match(input,match,r)
更改为std::regex_match(input,r)
来运行上述程序,发现它仍然返回false.
有人可以解释上面的例子,以及这些方法的一般用例吗?
regex_match
仅在匹配整个输入序列时返回true
,而即使只有一个子序列与regex
匹配,regex_search
也会成功。
引用N3337,
§28.11.2/2
regex_match
[重新匹配]
影响:确定正则表达式e
与所有字符序列[first,last)
之间是否存在匹配。...
如果存在此类匹配项,则返回true
,否则false
返回。
上面的描述是针对regex_match
重载,它将一对迭代器带到要匹配的序列。其余重载是根据此重载定义的。
相应的regex_search
过载描述为
§28.11.3/2
regex_search
[重新搜索]
影响:确定[first,last)
中是否存在与正则表达式e
匹配的某个子序列。...
如果存在此类序列,则返回true
,否则false
返回。
在您的示例中,如果您修改regex
以r{R"(.*?sd{2}s.*)"};
regex_match
,regex_search
将成功(但匹配结果不仅仅是日期,而是整个日期字符串(。
示例的修改版本的现场演示,其中regex_match
和regex_search
捕获并显示当天。
这很简单。 regex_search
查看字符串以查找字符串的任何部分是否与正则表达式匹配。 regex_match
检查整个字符串是否与正则表达式匹配。 作为一个简单的示例,给定以下字符串:
"one two three four"
如果我在该字符串上使用表达式 regex_search
"three"
,它将成功,因为"three"
可以在"one two three four"
中找到
但是,如果我改用regex_match
,它将失败,因为"three"
不是整个字符串,而只是其中的一部分。
- C++ std::regex 使用前瞻失败
- std::regex:匹配由数字和空格组成的字符串,并提取数字.如何?
- 你能防止 std::regex 在无效表达式上抛出异常吗?
- 在VC2015U3上,std::regex比boost::regex慢得多
- 将std::regex设置为静态的好主意吗
- std::regex and dual ABI
- C++11 std::regex后备选项
- 包含在 std::regex 搜索中,使用 std::regex_token_iterator 从 std::sub_m
- std::string references、std::regex和boost::filesystem的基本概念
- std::regex 是否保证了最坏情况下的时间复杂度?
- boost::regex 和std::regex之间的不一致?
- 使用 std::regex 拆分一行并丢弃空元素
- std::string to std::regex
- 用std :: Regex通过DOT解析数字
- C++ [std::regex] 尝试仅匹配中间有空格的数字
- std::regex总是可以识别区域设置吗?
- 是STD :: REGEX构造函数安全
- STD :: Regex不确定的行为
- std::regex对于用户定义的表达式安全吗?
- std::regex来识别多项式方程的系数