Search code examples
javascriptregexparentheses

parenthetical units in regex returning extra matches


I'm new to regex and have been struggling with one, and have abstracted my problem to the following issue:

var foo = "abc";
var array1 = match(/abc/);
var array2 = match(/a(b)c/);

array1 will of course contain only "abc", but array2 will contain both "abc" and also "b".
Why does array2 pick up "b" as well? This is a problem to me because I am matching some things inside braces like "{1 2a 3}", with a regex like /\{(\d(|a|b)\s?)+\}/, and the resulting array returns the empty string and "3" as well as the desired "{1 2a 3}".

Thank you!
Isaac


Solution

  • Use (?:) instead of ().

    /{(?:\d(|a|b)\s?)+}/
    

    When you use (), match return matched groups also. Groups are the part of the string that are correspondent to parts of the regular expression, which are in ().