Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex using recursion with groups

I am not certain if there’s any regex magic that can do this:

foo(f1, f2()) = bar { b1, b2 {}} //match all of this
foo(f3) // dont match this
bar{b3} // dont match this

what I am trying to do is capture an entire line if it contains this pattern:

\w+\((?:[^()]|(?RECURSION ON PARENTHESES))*\)\s*=\s*\w+{(?:[^{}]|(?RECURSION ON CURLY BRACKETS))*}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use regex subroutines:

\w+\s*(\((?:[^()]++|(?-1))*\))\s*=\s*\w+\s*({(?:[^{}]++|(?-1))*})

See the regex demo.

Details:

  • \w+ – one or more word chars
  • \s* – zero or more whitespaces
  • (\((?:[^()]++|(?-1))*\)) – a substring between paired nested parentheses
  • \s*=\s* – a = char enclosed with zero or more whitespaces
  • \w+\s* – one or more word chars, zero or more whitespaces
  • ({(?:[^{}]++|(?-1))*}) – a substring between paired nested curly braces.

Note the (?-1) recurses the latest capturing group pattern.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading