我想找到一个正则表达式,它将执行以下操作(使用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都失败。我以前的尝试是一个稍微compicated正则表达式:
(?:[^\(\)]*(\(.*?\)))*[^\(\)]*
可以描述如下
(?: # 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)
,catpuring只有QUUX。
我应该如何解决上述正则表达式?
你假定非嵌套好事,否则将不是一个常见问题 – 2011-05-19 16:18:33