Regex matching parentheses with =

Viewed 58

I'm trying to write a regex to filter out parameters of a handlebars call:

example call:

  117-tooltip classes=(concat (concat "productTile__product-availability " classes) " tooltip--small-icon productAvailability__tooltip") bla=(concat "test" "test2")

what my matches should be:

  • classes=(concat (concat "productTile__product-availability " classes) " tooltip--small-icon productAvailability__tooltip")
  • bla=(concat "test" "test2")

what my matches currently are:

  • (concat (concat "productTile__product-availability " classes) " tooltip--small-icon productAvailability__tooltip")
  • (concat "test" "test2")

my regex:

\((?>[^()]|(?R))*\)

I need to extend it so the structure must be something=(...(...)..) with an unknown number of matching parentheses.

How do I need to extend the regex to get the x= part also into it?

2 Answers

I would use:

\b\w+=.*?(?=\s+\w+=|$)

Demo

The idea behind this pattern is to match a key= followed by all content leading up to, but not including, either the next key, or the end of the input.

Explanation:

\b\w+=         match a KEY=
.*?            match all content up, but not including
(?=\s+\w+=|$)  assert that what follows is one or more
               whitespace characters followed by KEY= OR
               the end of the input

You can use a regex subroutine:

(\w+)=(\(((?>[^()]++|(?2))*)\))

See the regex demo. Details:

  • (\w+) - Capturing group 1: one or more word chars
  • = - a = char
  • (\(((?>[^()]++|(?2))*)\)) - Group 2 (needed for the regex subroutine to work):
    • \( - ( char
    • ((?>[^()]++|(?2))*) - Group 3: zero or more repetitions of one or more chars other than ( and ) or the whole Group 2 pattern recursed
    • \) - a ) char.
Related