javascript - 复杂正则表达式

标签 javascript regex

我试图找到一个正则表达式来执行以下操作(使用 Javascript)。我想获取一个字符串,其中包含一些标记,如 (token) 在括号内。我的目标是捕获标记(包括括号)。我将假设括号没有嵌套,并且每个左括号最终都会关闭。

我会使用的正则表达式是

[[^\(\)]*|(\(.*?\))]*

让我分解一下:

[            # Either of two things:
  [^\(\)]*   # the first is a substring not containing parentheses
|
  (          # the second is to be captured...
    \(.*?\)  # and should contain anything in parentheses - lazy match
  )
]*           # Any number of these blocks can appear

不用说,这行不通(否则我为什么要在这里问?):

var a = /[[^\(\)]*|(\(.*?\))]*/;
a.exec('foo(bar)');

它在 Firefox 和 Node 中都失败了。我之前的尝试是稍微复杂一些的正则表达式:

(?:[^\(\)]*(\(.*?\)))*[^\(\)]*

可以这样描述

(?:              # A non-capturing group...
  [^\(\)]*       # ...containing any number of non-parentheses chars
  (\(.*?\))      # ...followed by a captured token inside parentheses.
)*               # There can be any number of such groups
[^\(\)]*         # Finally, any number of non-parentheses, as above

这将在 foo(bar) 上运行,但在 foo(bar)(quux) 上将失败,仅捕获 quux。

How should I fix the above regex?

最佳答案

您不能在正则表达式中有任意数量的捕获组。使用/g 标志来完成此操作:s.match(/\([^\)]+\)/g)

关于javascript - 复杂正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6061589/

相关文章:

javascript - 仅包含数字和破折号的正则表达式

javascript - 正则表达式新手。在所有结束标签后添加空格

javascript - 使用 JavaScript 从 XML 节点检索内部文本时遇到问题

如果两个选择选项都有值,则 JavaScript 启用按钮

javascript - Highchart 突出显示具有自定义颜色的点之间的区域

regex - Raku 有没有一种快速的方法来查找和删除/替换非 ASCII 或格式错误的 utf8 字符?

regex - Perl 脚本将两个模式之间的行合并为一行并打印整个文件

php - 子域的正确正则表达式

javascript - Respond.js 不能跨域工作

php - 如何让鼠标悬停功能在多个图像上工作,每个图像都有单独的伴随文本?