regex implementation
I can't seem to get regular expressions to work in visual c++ 2005 express edition. I'm parsing a .h file for #define, and the below code errors:
System::Text::RegularExpressions::Regex^ blockDefine = gcnew System::Text::RegularExpressions::Regex("define\bEE_BLOCK_(\w*)\b");
System::Windows::Forms::MessageBox::Show(blockDefine->IsMatch("#define EE_BLOCK_VERSION 0").ToString());
The error is:
.\fileio.cpp(23) : warning C4129: 'w' : unrecognized character escape sequence
I don't understand why this isn't working. Ovbiously it's trying to escape the \w and it doesn't like that...but how do I fix it?
[650 byte] By [
eTape] at [2007-12-22]
The C++ compiler is eating up the backslash as its own meta character, where you intended it to be consumed by the regular expression parser. Since \w doesn't code for anything in C++, you get this warning.
To fix this, use two backslashes so that a single backslash reaches the regular expression parser.
System::Text::RegularExpressions::Regex^ blockDefine = gcnew System::Text::RegularExpressions::Regex("define\\bEE_BLOCK_(\\w*)\\b");
Aside: C# allows you to override meta-character parsing strings with @. e.g. string myString = @"leave\my\backslashes\alone";. I am not aware of an equivalent in C++/CLI, however.
Brian
Thanks, that worked. (My regex was messed up I wanted \s instead of \b, but that's a different story)
I would like to point out that MSDN was absolutly no help on this subject. If any1 knows a way to not use meta characters that would be nice, I hate having to escape every 3rd character in my regex. It makes them even more write only.
The treatment of metacharacters is documented in MSDN under http://msdn2.microsoft.com/en-us/library/8kc54dd5.aspx. Of course this isn't very discoverable--most people know this from basic C/C++ experience.
C++/CLI tries not to extend the syntax of the language more than it needs to, so this is probably why you have to rely on this knowledge to use regular expressions correctly. I agree that documentation could be improved so that fewer people will get frustrated by this. You may want to give some feedback on the corresponding MSDN help for regular expressions for C++/CLI programmers of this "gotcha."
Brian