tags:

views:

332

answers:

2

I'm writing a simple regex in c# to locate backslashes not preceded or followed by any backslashes:

Regex reg = new Regex(".*(?<!\\)\\(?!\\).*");

However, this statment generates an ArgumentException: "parsing ".(?" - Not enough )'s"

The group parentheses seem to match. Can anyone spot the problem?

+11  A: 

Put the @ symbol in front of your string, otherwise you need to double-escape the slashes (once for C#, and once for Regex).

Regex reg = new Regex(@".*(?<!\\)\\(?!\\).*");

or

Regex reg = new Regex(".*(?<!\\\\)\\\\(?!\\\\).*");
John Fisher
You nailed it. I don't know why someone downvoted this.
Jeremy Stein
thank goodness for string literals, double escaping just makes these more difficult to parse (for humans that is)
brism
+4  A: 

use the string literal @

Regex reg = new Regex(@".*(?<!\\)\\(?!\\).*");
hjb417