好的,我有这种情况,逗号在括号内,我想匹配仅在括号外的逗号。
Input : color-stop(50%,rgb(0,0,0)), color-stop(51%,rgb(0,0,0)), color-stop(100%,rgb(0,0,0)))
Output(i'm looking for):color-stop(50%,rgb(0,0,0))**,** color-stop(51%,rgb(0,0,0))**,** color-stop(100%,rgb(0,0,0)))
这是我的正则表达式:-
/(?![^(]*\)),/g
可悲的是,当有多个括号时它不起作用:(
最佳答案
这是非常适合您输入的正则表达式。
,(?![^()]*(?:\([^()]*\))?\))
解释:
, ','
(?! negative look ahead, to see if there is not:
[^()]* any character except: '(', ')' (0 or
more times)
(?: group, but do not capture (optional):
\( '('
[^()]* any character except: '(', ')' (0 or
more times)
\) ')'
)? end of grouping, ? after the non-capturing group makes the
whole non-capturing group as optional.
\) ')'
) end of look-ahead
限制:
此正则表达式的工作原理是假设括号的嵌套深度不会大于 2,即括号内的括号。如果输入中出现不平衡、转义或带引号的括号,它也可能会失败,因为它依赖于每个右括号对应一个左括号的假设,反之亦然。
关于javascript - 正则表达式只匹配逗号但不匹配多个括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26195975/