我试图找到一个正则表达式来执行以下操作(使用 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/