C++ regex not matching

  • C/++/#
  • Thread starter cheers00
  • Start date
  • #1
5
0

Main Question or Discussion Point

I am wondering why this is not matching. I tested my regular expression on notepad2 and it matches fine.


std::string line = " 10 0 5 0";
std::regex rgx("\s+\d+\s+\d+\s+\d+\s+\d+");

if (regex_match(line, rgx))
{
// do something...
int a = 2;
}
 

Answers and Replies

  • #2
D H
Staff Emeritus
Science Advisor
Insights Author
15,393
683
"\s" is a single character string. Containing what character? Who knows. That backslash s is a nonstandard escape sequence. Your code won't even compile on my computer. You need to use "\\s" to denote a backslash followed by an 's'. The same goes for all of your other single backslashes.
 
  • #3
33,494
5,186
I am wondering why this is not matching. I tested my regular expression on notepad2 and it matches fine.


Code:
std::string line = "		10			0		5		0";
std::regex rgx("\s+\d+\s+\d+\s+\d+\s+\d+");

if (regex_match(line, rgx))
 {
        // do something...
	 int a = 2;
 }
The only thing that occurs to me is that the string is terminated with an ASCII null char, possibly looking like \0, and your regex match string doesn't take that into account.

BTW, I replaced your font tags with [code] tags. Now your spaces are appearing.
 
  • Like
Likes 1 person
  • #4
Ibix
Science Advisor
Insights Author
6,206
4,838
Double up those \. The compiler is interpreting \s as a special character, so the regex engine is seeing something like s+, not \s+. Use \\s and \\d and you'll be fine.

Edit: must type quicker.
 
  • #5
33,494
5,186
Double up those \. The compiler is interpreting \s as a special character, so the regex engine is seeing something like s+, not \s+. Use \\s and \\d and you'll be fine.
Your explanation makes more sense than mine...
Edit: must type quicker.
 
  • #6
5
0
Double up those \. The compiler is interpreting \s as a special character, so the regex engine is seeing something like s+, not \s+. Use \\s and \\d and you'll be fine.

Edit: must type quicker.
doubling back slash worked. thank you
 
  • #7
Ibix
Science Advisor
Insights Author
6,206
4,838
!{a problem} :D
 

Related Threads on C++ regex not matching

Replies
14
Views
893
  • Last Post
Replies
4
Views
3K
Replies
7
Views
682
Replies
6
Views
1K
  • Last Post
Replies
2
Views
2K
Replies
3
Views
720
Replies
8
Views
3K
Replies
3
Views
2K
Top