正则表达式匹配括号与 =

时间:2020-12-24 13:33:19

标签: regex

我正在尝试编写一个正则表达式来过滤掉车把调用的参数:

示例调用:

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

我的匹配应该是什么:

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

我目前的匹配对象是:

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

我的正则表达式:

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

我需要扩展它,所以结构必须是 something=(...(...)..) 与未知数量的匹配括号。

我需要如何扩展正则表达式才能将 x= 部分也加入其中?

2 个答案:

答案 0 :(得分:3)

我会使用:

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

Demo

这种模式背后的想法是匹配一个 key= 后跟所有导致但不包括下一个键或输入结尾的内容。

说明:

\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

答案 1 :(得分:3)

您可以使用 regex subroutine

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

参见regex demo详情

  • (\w+) - 捕获第 1 组:一个或多个单词字符
  • = - = 字符
  • (\(((?>[^()]++|(?2))*)\)) - 第 2 组(正则表达式子例程工作所需):
    • \( - ( 字符
    • ((?>[^()]++|(?2))*) - 第 3 组:除 () 之外的一个或多个字符的零次或多次重复或整个第 2 组模式的递归
    • \) - 一个 ) 字符。