正则表达式只匹配逗号,但不在多个括号内

时间:2014-10-04 18:42:02

标签: javascript regex

好的,我有这种情况,其中逗号在括号内,我想匹配仅在括号内的逗号。

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

可悲的是,当有多个括号时它不起作用:(

Regex

1 个答案:

答案 0 :(得分:6)

这是正则表达式,非常适合您的输入。

,(?![^()]*(?:\([^()]*\))?\))

DEMO

<强>解释

,                        ','
(?!                      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