1

I'm trying to match strings similar to Lookup("lookup name", "lookup key") so I can replace the "lookup key".

I've got a pattern where the lookup key is "3" or 3:

[lL][oO][oO][kK][uU][pP]\(.*?,[ ]*("3"|3)\)

But when I use it on the following input string (which has nested calls) it matches the entire string except for the last parenthesis.

LOOKUP("lookup name1",LOOKUP("lookup name2",3))

How do I get it to just match the last part LOOKUP("lookup name2",3) ?

camios
  • 182
  • 13
  • 2
    `"...has nested..."` BZZZZZ. Stop using a regex immediately. Regular expressions are not stateful, and thus are not designed to be used in grammars like this. See this: [Can regular expressions be used to match nested patterns?](http://stackoverflow.com/questions/133601/can-regular-expressions-be-used-to-match-nested-patterns) – Jonathon Reinhart Jun 24 '14 at 05:07
  • The example `LOOKUP("lookup name1",LOOKUP("lookup name2",3))` is simple, and doesn't require understanding the nested structures. Can you also have `LOOKUP(LOOKUP("lookup name1","lookup name2"), 3)`? Because that one is more challenging. – Kobi Jun 24 '14 at 05:35
  • @JonathonReinhart, yep I'm aware. – camios Jun 24 '14 at 07:01
  • I was mucking about with a regex tester just to see what sort of input strings would match and I couldn't work out why the example I gave didn't result in a match. I'm still interested to see if there is a pattern which doesn't require a negation ([^something]) to work – camios Jun 24 '14 at 07:07

1 Answers1

4

Directly Matching and Replacing the Key

This matches your lookup key directly!

(?i)(?<=lookup\([^(),]*,)[^()]*?(?=\))

See demo.

You can then replace it with whatever you like:

resultString = Regex.Replace(yourString, @"(?i)(?<=lookup\([^(),]*,)[^()]*?(?=\))", "whatever");

This works because the .NET regex engine supports infinite lookbehinds.

Explanation

  • (?i) puts us in case-insensitive mode
  • (?<=lookup\([^(),]*,) is a lookbehind that asserts that what precedes us is the literal lookup(, then any characters that are not parentheses or commas, then a comma
  • The character class [^()]*? lazily matches any characters that are not parentheses (this is our match!)
  • The lookahead (?=\) asserts that what follows is a closing parenthesis

Reference

zx81
  • 41,100
  • 9
  • 89
  • 105
  • Hey btw I notice you haven't yet voted on Stack. Do you know how to do it? You click the Up arrow above the checkmark, to the left of the question. If this answer helps, and for all answers you find helpful, please consider voting up as this is how the rep system works here.:) No obligation of course. Thanks!!! – zx81 Jun 24 '14 at 07:18