Reputation: 20730
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.
Upvotes: 0
Views: 204
Reputation: 111
Use this instead:
\\[[^\\]]+\\]
Your regex is partially wrong because of (.*)
, which makes your pattern to allow any character between [
and ]
, which includes [
and ]
.
Upvotes: 0
Reputation: 361564
str.match(/\[(.*?)\]/g);
Use a ?
modifier to make the *
quantifier non-greedy. A non-greedy quantifier will match the shortest string possible rather than the longest, which is the default.
Upvotes: 3
Reputation: 11342
Use this instead:
var str = 'I know [foo] and [bar] about Regex';
str.match(/\[([^\[\]]*)\]/g);
Your regex is partially wrong because of (.*)
, which makes your pattern to allow any character between [
and ]
, which includes [
and ]
.
Upvotes: 2
Reputation: 388316
Try
var array = 'I know [foo] and [bar] about Regex'.match(/(\[[^\]]+\])/g)
Upvotes: 0