dthree
dthree

Reputation: 20730

Regex Matching - Content within brackets

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

Answers (4)

Anitha
Anitha

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

John Kugelman
John Kugelman

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

Danilo Valente
Danilo Valente

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

Arun P Johny
Arun P Johny

Reputation: 388316

Try

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

Upvotes: 0

Related Questions