Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

\s not working in C++ regex

Tags:

c++

regex

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++.

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;
}

Input: a b
Output: No match

https://ideone.com/ULJrkQ

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

Input: azb
Output: Matched

http://ideone.com/4yBS4Z

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.

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.

like image 442
Overlord Avatar asked Sep 05 '25 03:09

Overlord


1 Answers

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;
}
like image 112
paul-g Avatar answered Sep 07 '25 19:09

paul-g