2011-05-19 69 views
3

我想找到一个正则表达式,它将执行以下操作(使用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。

我应该如何解决上述正则表达式?

+0

你假定非嵌套好事,否则将不是一个常见问题 – 2011-05-19 16:18:33

回答

4

在正则表达式中不能有任意数量的捕获组。使用/ g标志来代替实现此目的:s.match(/\([^\)]+\)/g)

+0

我必须承认我很困惑。虽然你的例子确实有效,但是反转 - 即使用regex.exec(字符串) - 不会。 : - ? – Andrea 2011-05-19 16:23:41

+0

iirc'exec'不支持'/ g'多重匹配 – 2011-05-19 16:35:15

1

如果你的目的是捕获括号(包括分隔符)的内部令牌然后进行简单的正则表达式,如:

\([^)]*?\) 

将工作。

2

这工作发现 - 在Chrome测试

<your string here>.match(/(\(.*?\))/g) 

它返回匹配的数组:

str = 'Content(cap)(cap2)(cap3)' 
str.match(/(\(.*?\))/g) 
-> ["(cap)", "(cap2)", "(cap3)"]