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.
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.
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 ]
.
尝试
var array = 'I know [foo] and [bar] about Regex'.match(/(\[[^\]]+\])/g)
Use this instead:
\\[[^\\]]+\\]
Your regex is partially wrong because of (.*)
, which makes your pattern to allow any character between [
and ]
, which includes [
and ]
.
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.