non-capture group still showing in match

后端 未结 2 1408
夕颜
夕颜 2020-12-16 10:27

I know this topic has been thoroughly covered on StackOverflow, but I can\'t for the life of me get my regular expression to work. So without further repetitive ado ...

相关标签:
2条回答
  • 2020-12-16 10:33

    A non-capturing group is basically just a non-group ― a way to use parentheses without actually treating that part of the pattern as a group.

    It looks like what you're actually looking for are the "match prefix but exclude" group (?<=) and the "match suffix but exclude" group (?=).

    Note: This type of group does not seem to be supported in Internet Explorer.

    If you use these, you get the desired result:

    var str = "<p model='cat'></p><p model='dog'></p><p model='horse'></p>";
    var regex = /(?<=model=')[^']*(?=')/g
    var matches = str.match(regex);
    
    console.log(matches);

    0 讨论(0)
  • 2020-12-16 10:40

    The entire match will always be group 0, you need to access that specific group (group 1 in this case since the first group is non-capture), you can do it like this:

    var str = "<p model='cat'></p>";
    var regex = /(?:model=')(.*)(?:')/g
    var match = regex.exec(str);
    alert(match[1]); // cat

    Fiddle

    Also, I suppose you are probably wanting several matches within str, you could do that like this:

    var str = "<p model='cat'></p><p model='dog'></p><p model='horse'></p>";
    var regex = /(?:model=')([^']*)/g
    var matches = [];
    var match;
    while (match = regex.exec(str)) {
      matches.push(match[1]);
    }
    alert(matches); // cat,dog,horse

    Fiddle

    0 讨论(0)
提交回复
热议问题