简体   繁体   中英

Regex returning content within multiple square brackets

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.

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 + .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM