Night Train
Night Train

Reputation: 781

Regex Pattern Using Brackets

Simple question here guys. I'm attempting to create a pattern to use with a Regex in C#.

Here is my attempt:

"(value\":\[\[\"([A-Za-z0-9]+(?:-{0,1})[A-Za-z0-9]+)\"\]\])"

However for some reason when I go to compile this I get "Unrecognized escape sequence" on the brackets. Can I not simply use \ to escape the brackets?

The strings I'm searching for have the form of

value":[["AB-AB"]]

or

value":[["ABAB"]]

and I'd like to grab group[1] from the results.

Upvotes: 1

Views: 82

Answers (2)

hwnd
hwnd

Reputation: 70722

I would recommend placing your pattern inside a verbatim string literal while implementing a negated character class to match the context; then reference the first group to grab the match results.

String s = @"I have value"":[[""AB-AB""]] and value"":[[""ABAB""]]";
foreach (Match m in Regex.Matches(s, @"value"":\[\[""([^""]+)""]]"))
         Console.WriteLine(m.Groups[1].Value);

Output

AB-AB
ABAB

Upvotes: 2

pquest
pquest

Reputation: 3290

The C# compiler by default disallows escape sequences it does not recognize. You can override this behavior by using "@" like this:

@"(value\"":\[\[\""([A-Za-z0-9]+(?:-{0,1})[A-Za-z0-9]+)\""\]\])"

Edit:

The @ sign is a little more complicated than that. To quote @Guffa:

A @ delimited string simply doesn't use backslash for escape sequences.

Furthermore it should be noted that the replacement for \" in such a string is ""

Upvotes: 3

Related Questions