regex "\\" does not match string("\\")

The title says it all.
I have been trying to run this for a while and can't figure out why;

1
2
3
4
regex ex("\\");
string str="\\";
bool m1=regex_search(str,ex);
cout<<(m1?"match":"not match")<<endl;


This always prints not match, anyone know the reason why?
'\' is an escape character in C++ and in regex... so when you type "\\" in code, it's actually a single \ character.

So your str string contains a single slash character, and your regex string is also a single slash character. But since regex uses slashes to escape certain codes, a single slash character doesn't mean anything.

So you need to escape both of them:

1
2
3
regex ex("\\\\"); // <- C++ escapes \, so this is actually "\\", which regex will then escape to '\'
string str="\\"; // <- C++ escapes to '\'
...



EDIT:

One of the things lacking in C++ is the ability for "raw" strings where characters don't have to be escaped. Working with regex is actually a big pain without raw strings.
Last edited on
@Disch

Thank you very much, I am still new to regex expressions. I thought I had already escaped the special charachters with regex. I can now see the benefit of having raw strings.

Thanks again.
> One of the things lacking in C++ is the ability for "raw" strings where characters don't have to be escaped.
> Working with regex is actually a big pain without raw strings.

See : http://www.stroustrup.com/C++11FAQ.html#raw-strings
Topic archived. No new replies allowed.