javascript - 正则表达式只匹配逗号但不匹配多个括号

标签 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

最佳答案

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

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

DEMO

解释:

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

相关文章:

javascript - 通过 select_list 中的文本而不是通过索引进行选择

javascript - 在数组中找到精确的数字匹配?

regex - 带有多个单词的 git 匹配标签

python - 带有日语字符的 re.sub

javascript - jQuery 选择器选择每个字母的第一个元素

python - 从正则表达式中的文件名解析日期

javascript - 如何通过 Javascript 在 Flowplayer 中更改视频(并立即开始播放)?

javascript - 调整 div 的高度 - 基于分辨率和元素数

javascript - 如何在 javascript 中使用正则表达式、匹配和执行从文本中删除重复项

php - 检查字符是否在 PHP 中的单词中