Warm tip: This article is reproduced from serverfault.com, please click

Regex returning content within multiple square brackets

发布于 2020-11-28 03:00:13

I am using Regex with JavaScript and want to return the content within the square brackets (including the brackets themselves) in the following string:

var str = '##abde[fgh]ijk[mn]op';
var brackets = str.match(/\[.{1,}\]/g); //["[fgh]ijk[mn]"]

I wanted brackets to return ["[fgh]", "[mn]"], rather than the content (ijk) outside of the brackets. How can this be fixed? Thank you.

Questioner
user504557
Viewed
0
costaparas 2020-11-28 11:08:59

The problem here is that . matches any character (including square brackets).

You can use a character class like:

[^\]]

to match any character except square brackets.

So this should work for you:

str.match(/\[[^\]]{1,}\]/g);

Better would be this:

str.match(/\[[^\]]+\]/g);

It's a little neater since {1,} is semantically equivalent to +.