\s 在 C++ 正则表达式中不起作用

Ove*_*ord 4 c++ regex

我昨天开始学习正则表达式,在学习时,我看到 \s 用于空白字符。但是,由于某种原因,每当我输入空格时,C++ 中都不会检测到它。

代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

输入:ab
输出:不匹配

https://ideone.com/ULJrkQ

如果我用上面的代码替换\\s\\w输入如下内容:

输入:azb
输出:匹配

http://ideone.com/4yBS4Z

我不明白为什么 \s 根本拒绝工作。我在网上浏览了这个问题的答案,但无法找到到底是什么原因造成的。

我使用带有 GNU/GCC 编译器的 CodeBlocks 16 IDE,在 Windows 上启用了 C++11 支持,在 IDEONE 上启用了 C++14 (GCC 5.1)。

任何帮助将非常感激。谢谢。

pau*_*l-g 5

只要确保阅读整行,一种解决方案是使用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;
}
Run Code Online (Sandbox Code Playgroud)