Regex Pattern to ignore the inner parenthesis in the input string

Viewed 129

I have been struggling to find the solution for below requirement

Input string is Sum(Spec("any text1" : "any text2"),spec("any text3" : "any text4")) I want to match the string spec("any text1" : "any text2") and spec("any text3" : "any text4"))

pattern which I tried is Spec\(([^)]*)\) enter image description here

This pattern works for above input , but if any of the any text1 ,any text2, any text3 and any text4 contains parenthesis then it fails to match

ex input Sum(Spec("any text1 with (bracket)" : "any text2"),spec("any text3" : "any text4"))

enter image description here

It is also possible that text can contain the quotation marks as well "chassis \"4\"".

1 Answers

You can use

(?is)\bSpec\((?>"[^"\\]*(?:\\.[^"\\]*)*"|[^()]|(?<c>)\(|(?<-c>)\))*(?(c)(?!))\)

See the .NET regex demo.

Details:

  • (?is) - case insensitive modifier
  • \b - a word boundary
  • Spec\( - Spec( text
  • (?> - start of an atomic group:
    • "[^"\\]*(?:\\.[^"\\]*)*" - a "..." string that may contain escaped " chars
    • | - or
    • [^()] - any one char other than ( and )
    • | - or
    • (?<c>)\( - ( char is matched and an empty value is pushed on to Group c stack
    • | - or
    • (?<-c>)\) - ) char is matched and an empty value is popped off the Group c stack
  • )* - end of the atomic group, repeat zero or more times
  • (?(c)(?!)) - a conditional construct: if Group c stack is not empty fail, trigger backtracking
  • \) - a ) char.
Related