Man*_*mar 30 c++ regex c++11 visual-studio-2013 gcc4.9
编写下面的程序是为了使用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"(\s\d{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";
}
}
Run Code Online (Sandbox Code Playgroud)
Did Not Found
Found
25
Run Code Online (Sandbox Code Playgroud)
为什么false在这种情况下第一个正则表达式方法返回?在regex似乎是正确的那么理想情况下都应该已经返回true.我通过更改std::regex_match(input,match,r)to 运行上面的程序std::regex_match(input,r),发现它仍然返回false.
有人可以解释上面的例子,一般来说,使用这些方法的案例吗?
Pra*_*ian 27
regex_match仅true在整个输入序列匹配时返回,而regex_search即使只有子序列匹配,也会成功regex.
引自N3337,
§28.11.2/ 2
regex_match[re.alg.match]
效果:确定正则表达式e和所有字符序列[first,last)之间是否匹配.如果存在这样的匹配则...返回true,false否则返回.
上面的描述适用于regex_match将一对迭代器与序列匹配的重载.剩余的重载是根据这种过载来定义的.
相应的regex_search过载描述为
§28.11.3/ 2
regex_search[re.alg.search]
效果:确定是否存在与正则表达式匹配的子序列[first,last)e.如果存在这样的序列则...返回true,false否则返回.
在您的示例中,如果您regex将r{R"(.*?\s\d{2}\s.*)"};两者都修改为regex_match并且regex_search将成功(但匹配结果不仅仅是日期,而是整个日期字符串).
现场演示的其中一天被捕获且由显示在您的例子的修改版本regex_match和regex_search.
Ben*_*ley 16
这很简单.regex_search查看字符串以查找字符串的任何部分是否与正则表达式匹配.regex_match检查整个字符串是否与正则表达式匹配.举个简单的例子,给出以下字符串:
"one two three four"
Run Code Online (Sandbox Code Playgroud)
如果我regex_search在表达式上使用该字符串"three",它将成功,因为"three"可以在中找到"one two three four"
但是,如果我使用regex_match它,它将失败,因为"three"它不是整个字符串,而只是它的一部分.
| 归档时间: |
|
| 查看次数: |
15666 次 |
| 最近记录: |