\ s在C ++正则表达式中不起作用 [英] \s not working in C++ regex

查看:81
本文介绍了\ s在C ++正则表达式中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I started learning about regex yesterday and while learning, I saw that \s is used for whitespace characters. However, for some reason, whenever i enter a space, it is not detected in 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;
}

输入:a b
输出:不匹配

Input: a b
Output: No match

https://ideone.com/ULJrkQ

如果我在上述代码中用 \\ w 替换 \\ s 并输入如下内容:

if I replace \\s with \\winside the above code and input something like this:

输入:azb
输出:匹配

Input: azb
Output: Matched

http://ideone.com/4yBS4Z

我不明白为什么\ s只是拒绝工作.我在线浏览了有关此问题的答案,但找不到确切原因.

I don't understand why \s simply refuses to work. I browsed online for an answer to this problem but wasn't able to find what exactly is causing this.

我将CodeBlocks 16 IDE与GNU/GCC编译器一起使用,并在Windows上启用了C ++ 11支持,并在IDEONE上启用了C ++ 14(GCC 5.1).

I use CodeBlocks 16 IDE with GNU/GCC compiler with C++11 support enabled on Windows and C++14 (GCC 5.1) on IDEONE.

任何帮助将不胜感激.谢谢.

Any help would be much appreciated. Thanks.

推荐答案

请确保您已阅读整行,一种解决方案是使用 std :: getline(cin,str)代替<代码> cin>>str .请参见在此处使用一个Ideone的示例:

Just make sure you read the whole line, one solution is to use std::getline(cin, str) instead of cin >> str. See the example working here one 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;
}

这篇关于\ s在C ++正则表达式中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆