0

This is a fast question, I just don't know many Regex tricks and can't find documentation for this exact point:

Lets say I have the string:

'I know [foo] and [bar] about Regex'

I want to do a JS Regex pattern that makes an array of each bracket encapsulation. Result:

['[foo]', '[bar]']

I currently have:

str.match(/\[(.*)\]/g);

But this returns:

'[foo] and [bar]'

Thanks.

4

4 回答 4

3
str.match(/\[(.*?)\]/g);

使用?修饰符使*量词非贪婪。非贪婪量词将匹配可能的最短字符串而不是最长字符串,这是默认值。

于 2013-06-14T03:40:37.203 回答
2

改用这个:

var str = 'I know [foo] and [bar] about Regex';
str.match(/\[([^\[\]]*)\]/g);

您的正则表达式部分错误是因为(.*),这使您的模式允许and之间的任何字符,其中包括and 。[][]

于 2013-06-14T03:40:08.643 回答
0

尝试

var array = 'I know [foo] and [bar] about Regex'.match(/(\[[^\]]+\])/g)
于 2013-06-14T03:39:55.343 回答
0

改用这个:

\\[[^\\]]+\\]

您的正则表达式部分错误是因为(.*),这使您的模式允许 and 之间的任何字符[]其中包括[and ]

于 2014-11-15T07:28:02.923 回答