C/C++ Why is my C++ regex not matching?

  • Thread starter Thread starter cheers00
  • Start date Start date
  • Tags Tags
    C++
AI Thread Summary
The discussion revolves around issues with a regular expression not matching as expected in C++. The original regex used a single backslash for escape sequences, which caused compilation errors. It was clarified that the correct format requires doubling the backslashes, changing "\s" to "\\s" and "\d" to "\\d". Additionally, there was a suggestion that an ASCII null character at the end of the string might affect the match. After implementing the correct escape sequences, the issue was resolved, and the regex began matching successfully.
cheers00
Messages
5
Reaction score
0
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;
}
 
Technology news on Phys.org
"\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.
 
cheers00 said:
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[/color]] tags. Now your spaces are appearing.
 
  • Like
Likes 1 person
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.
 
Ibix said:
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...
Ibix said:
Edit: must type quicker.
 
Ibix said:
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
 
!{a problem} :D
 
Back
Top