3

I'm trying to get the content in between square brackets within a string but my Regex isn't working.

RegExp: /\[([^\n\]]+)\]/g

It returns the correct match groups on regex101 but when I try something like '[a][b]'.match(/\[([^\n\]]+)\]/g), I get ['[a]', '[b]'] instead of ['a', 'b'].

I can get the correct results if I iterate through and do RegExp.exec, but from looking at examples online it seems like I should be able to get the match groups using String.match

2
  • You will get the matched groups if you drop the /g modifier. Commented Jun 24, 2014 at 19:26
  • When you're researching JavaScript or browser APIs, always be sure to check the Mozilla Developer Network (MDN). In this case, their documentation of the .match() method clearly spells out the behavior. Commented Jun 24, 2014 at 19:33

1 Answer 1

6

You're using the String .match() method, which has different behavior from RegExp .exec() in the case of regular expressions with the "g" flag. The .match() method gives you all the complete matches across the entire searched string for "g" regular expressions.

If you change your code to

/\[([^\n\]]+)\]/g.exec('[a][b]')

you'll get the result you expect: an array in which the first entry (index 0) is the entire match, and the second and subsequent entries are the groups from the regex.

You'll have to iterate to match all of them:

var re = /\[([^\n\]]+)\]/g, search = "[a][b]", bracketed = [];
for (var m = null; m = re.exec(search); bracketed.push(m[1]));
Sign up to request clarification or add additional context in comments.

7 Comments

This is not correct; your example solution yields ["[a]", "a"]
match is just to test a string for match - it uses the full pattern, not caring about any match groups. Thus the result will always be a "full-pattern-match".
@EdCottrell yes, and that is the correct answer. The first entry in the array is the complete match, and the second is the content of the parenthesized group.
I understand how .exec works, but your example doesn't tell OP how to find a and b, as requested.
@dognose that is not true for regular expressions without the "g" flag. In that case, the return value is the same as it would be from the RegExp .exec() call.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.