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?

2 Answers 2

16

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(".*(?<!\\\\)\\\\(?!\\\\).*");
Sign up to request clarification or add additional context in comments.

1 Comment

thank goodness for string literals, double escaping just makes these more difficult to parse (for humans that is)
4

use the string literal @

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.