JavaScript RegExp matching group takes unwanted parentheses

This question already has an answer here:

  • How do you access the matched groups in a JavaScript regular expression? 14 answers

  • In order to work with subpatterns, there is no easy shortcut.

    Instead, you have to repeatedly execute the regex on the string and collect the subpattern you want. Something like this:

    var text = "do[A]and[B]",
        regexp = /[(w+)]/g,
        result = [], match;
    while(match = regexp.exec(text)) {
        result.push(match[1]);
    }
    

    For this particular case you don't need capturing groups:

    >>> "do[A]and[Bbbb]".match(/w+(?=])/g);
    ["A", "Bbbb"]
    

    will do.

    链接地址: http://www.djcxy.com/p/76796.html

    上一篇: 匹配冒号后和新行之前的文本

    下一篇: JavaScript RegExp匹配组采用不需要的括号