Odrade
Odrade

Reputation: 7619

Error parsing regex pattern

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?

Upvotes: 2

Views: 7405

Answers (2)

Hasani Blackwell
Hasani Blackwell

Reputation: 2056

use the string literal @

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

Upvotes: 4

John Fisher
John Fisher

Reputation: 22717

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(".*(?<!\\\\)\\\\(?!\\\\).*");

Upvotes: 16

Related Questions