Meredith
Meredith

Reputation: 940

Regex negative lookahead in c#

I need to match ["this" but not :["this"

I have this code:

        Match match = Regex.Match(result, @"\[""(.*?)""",
            RegexOptions.IgnoreCase);

        while (match.Success)
        {
            MessageBox.Show(match.Groups[1].Value.Trim());
        }

I have tried the pattern @"(?!:)\[""(.*?)""", but it still match :["this". Whats the pattern I need to achieve this?

Upvotes: 3

Views: 5628

Answers (3)

QuinnG
QuinnG

Reputation: 6424

I used RegexBuddy (I love that app) set to .NET and got the following expression:

@"(?<!:)\[""(.*?)"""

Upvotes: 3

LukeH
LukeH

Reputation: 269298

You're doing a negative lookahead when you should be doing a negative lookbehind. Try this instead:

Match match = Regex.Match(result, @"(?<!:)\[""(.*?)""", RegexOptions.IgnoreCase);

Upvotes: 2

AakashM
AakashM

Reputation: 63340

You are looking ahead (rightwards in the string) when you want to be looking behind (leftwards in the string).

Try @"(?<!:)\[""(.*?)""" instead.

Upvotes: 5

Related Questions