Reputation: 1098
I admit it's been a while since I've worked with C++, but from what I can tell, my code should work. I'm trying to replace/remove all block comments from a file containing code. I put the whole file I'm searching into a string, and the string contains newline characters.
Here's my code
std::tr1::regex rx1("[/][*][\S\s]*?[*][/]");
stringName = std::regex_replace(stringName, rx1, std::string(""));
As far as I can tell, this should match /*anything in here including new lines */
I've even tested it on http://gskinner.com/RegExr/, where it matches block comments perfectly. Problem is, block comments aren't being replaced. Is this some kind of TR1 specific bug?
Upvotes: 2
Views: 919
Reputation: 1098
Lightness Races in Orbit pushed me along the right path, but turns out the * and ? cannot be used on arguments within [] brackets. The way to do that is use a noncapturing group which has or statements.
Code to find multi-line block comments:
std::tr1::regex rx3("[/][*](?:\s|.|\n)*?[*][/]");
(?:expression) is how to make a noncapturing group. You can apply the * and ? to the outside of that. Inside of it, use | as an or statement.
Upvotes: 1
Reputation: 385325
You have to consider that there are layers to what you're doing.
First, you're building a string inside a string literal. To a human it looks like a regular expression, but the string literal doesn't care.
That string literal contains, among other things, the special characters that are yielded by \S
and \s
respectively (just like how \n
is special).
Then, you're passing this string — special characters and all — to the regex engine.
Instead, you do need to perform escaping of the backslashes, just for the string literal:
std::tr1::regex rx1("[/][*][\\S\\s]*?[*][/]")
The regex engine will then see the expression properly:
[/][*][\S\s]*?[*][/]
Also, I'd check whether tr1's engine requires delimiters. They're usually a good idea.
Upvotes: 3