我昨天开始学习正则表达式,在学习时,我看到 \s 用于空白字符。但是,由于某种原因,每当我输入空格时,C++ 中都不会检测到它。
Code:
#include <iostream>
#include <regex>
using namespace std;
int main() {
string str;
cin>>str;
regex e("a+\\s+b+");
bool found = regex_match(str,e);
if (found)
{
cout<<"Matched";
}
else
{
cout<<"No Match";
}
return 0;
}
输入:a b
输出:不匹配
https://ideone.com/ULJrkQ
如果我更换\\s
with \\w
在上面的代码中并输入如下内容:
输入:azb
输出:匹配
http://ideone.com/4yBS4Z
我不明白为什么 \s 根本拒绝工作。我在网上浏览了这个问题的答案,但无法找到到底是什么原因造成的。
我使用带有 GNU/GCC 编译器的 CodeBlocks 16 IDE,在 Windows 上启用了 C++11 支持,在 IDEONE 上启用了 C++14 (GCC 5.1)。
任何帮助将非常感激。谢谢。
只要确保您阅读整行,一种解决方案是使用std::getline(cin, str)
代替cin >> str
。请参阅工作示例这里有一个 Ideone:
#include <iostream>
#include <regex>
using namespace std;
int main() {
string str;
getline(cin, str);
regex e("a+\\s+b+");
if (regex_match(str,e))
cout<<"Matched";
else
cout<<"No Match";
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)