1

I'm using the following regex to match the contents of any datascript script referencing a specific UDF:

\[?shared3\]?\.\[?stringsum\]?(((?'Open'\()[^()]*)+((?'Close-Open'\))[^()]*)+)*

it matches any instance of:

Shared3.StringSum(<some contents here>)

Using the balancing groups, I'm trying to also support cases like:

Shared3.StringSum(SomeOtherMethod('input') + AnotherMethod('input'))

However, I'm running into trouble, when the input is like:

Shared3.StringSum(SomeOtherMethod('input') + AnotherMethod('input')) + ThirdMethod('input')

In the last case, my regex also matches the ThirdMethod('input') part.

Is there any way I can alter my regex, so it stops matching as soon as the "parentheses count" is 0?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
PaulVrugt
  • 1,682
  • 2
  • 17
  • 40
  • 1
    Try `\[?shared3]?\.\[?stringsum]?\(((?>[^()]+|(?'Open'\()|(?'Close-Open'\)))*)\)`, see [demo](http://regexstorm.net/tester?p=%5c%5b%3fshared3%5d%3f%5c.%5c%5b%3fstringsum%5d%3f%5c%28%28%28%3f%3e%5b%5e%28%29%5d%2b%7c%28%3f%27Open%27%5c%28%29%7c%28%3f%27Close-Open%27%5c%29%29%29*%29%5c%29&i=Shared3.StringSum%28SomeOtherMethod%28%27input1%27%29+%2b+AnotherMethod%28%27input2%27%29%29%0d%0aShared3.StringSum%28SomeOtherMethod%28%27input1%27%29+%2b+AnotherMethod%28%27input2%27%29%29+%2b+ThirdMethod%28%27input%27%29&o=i). – Wiktor Stribiżew Apr 20 '20 at 14:27
  • Great, this fixes the issue. It isn't the exact regex I need, because of some other issues, but I was able to solve them. – PaulVrugt Apr 20 '20 at 14:51
  • What other issues? If it fixes the current issue it is a valid solution. Please edit the question if you want me to adjust it. – Wiktor Stribiżew Apr 20 '20 at 14:55
  • 1
    These other issues are unrelated to the question scope, so your answer is correct. No reason to panic :) Thank you! – PaulVrugt Apr 20 '20 at 15:01

1 Answers1

3

You may use

\[?shared3]?\.\[?stringsum]?\(((?>[^()]+|(?'Open'\()|(?'Close-Open'\)))*)\)

See the regex demo

Details

  • \[?shared3]? - an optional [, shared, and an optional ]
  • \. - a dot
  • \[?stringsum]? - an optional[,stringsum, and an optional]`
  • \( - a (
  • ((?>[^()]+|(?'Open'\()|(?'Close-Open'\)))*) - Group 1: one or more occurrences of
    • [^()]+| - 1+ chars other than ( and ), or
    • (?'Open'\()| - Group "Open": pushes ( into group stack
    • (?'Close-Open'\)) - Group "Close" and "Open": pops the ) from the Open group stack and saves the current level substring into Close group
  • \) - a ) char to finish things up
PaulVrugt
  • 1,682
  • 2
  • 17
  • 40
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563