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 \\w
inside 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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With