Regex find all matches EXCEPT those surrounded by characters

Viewed 70

I have the following regular expression to find all of the instances of {word} in my string. In the following string, this (correctly) matches {eeid} and {catalog}:

Expression {([^:]*?)}

String being searched {?:participants::lookup(.,{eeid},{catalog})}

Now - I need to "escape" one of those values, so it is NOT matched/replaced. I'm trying to use double square brackets to do so:

{?:participants::lookup(.,{eeid},[[{catalog}]])}

How can I adjust my regular expression so it ignores {catalog} (enclosed in [[ ]]) but finds {eeid}?

1 Answers

You can use

(?<!\[\[)\{([^:{}]*)}(?!]])

See the .NET regex demo.

Details

  • (?<!\[\[) - a negative lookbehind that fails the match if there is [[ immediately to the left of the current location
  • \{ - a { char
  • ([^:{}]*) - Group 1: any zero or more chars other than :, { and }
  • } - a } char
  • (?!]]) - a negative lookahead that fails the match if there is ]] immediately to the right of the current location.

See the C# demo:

var s = "{?:participants::lookup(.,{eeid},[[{catalog}]])}";
var rx = @"(?<!\[\[)\{([^:{}]*)}(?!]])";
var res = Regex.Matches(s, rx).Cast<Match>().Select(x => x.Groups[1].Value);
foreach (var t in res)
    Console.WriteLine(t);

// => eeid
Related