JavaScript Regex Global Match Groups

前端 未结 7 740
感动是毒
感动是毒 2020-11-28 10:50

Update: This question is a near duplicate of this

I\'m sure the answer to my question is out there, but I couldn\'t find the words to express it suc

相关标签:
7条回答
  • 2020-11-28 11:22

    EDIT: This won't work in javascript, but it does work in java. Sorry bout that.

    yes, it's called a "look ahead" and a "look behind"

    (?<=').*?(?=')
    
    • (?=') looks ahead for the '
    • (?<=') looks behind for the '

    test it out here

    0 讨论(0)
  • 2020-11-28 11:27

    Try something like input.replace(regex, "$1") to get the results of your capture group.

    0 讨论(0)
  • There is an ECMAScript proposal called String.prototype.matchAll() that would fulfill your needs.

    0 讨论(0)
  • 2020-11-28 11:36

    To do this with a regex, you will need to iterate over it with .exec() in order to get multiple matched groups. The g flag with match will only return multiple whole matches, not multiple sub-matches like you wanted. Here's a way to do it with .exec().

    var input = "'Warehouse','Local Release','Local Release DA'";
    var regex = /'(.*?)'/g;
    
    var matches, output = [];
    while (matches = regex.exec(input)) {
        output.push(matches[1]);
    }
    // result is in output here
    

    Working demo: http://jsfiddle.net/jfriend00/VSczR/


    With certain assumptions about what's in the strings, you could also just use this:

    var input = "'Warehouse','Local Release','Local Release DA'";
    var output = input.replace(/^'|'$/, "").split("','");
    

    Working demo: http://jsfiddle.net/jfriend00/MFNm3/

    0 讨论(0)
  • 2020-11-28 11:37

    String.prototype.matchAll is now well supported in modern browsers as well as Node.js. This can be used like so:

    const matches = Array.from(myString.matchAll(/myRegEx/g)).map(match => match[1]);
    

    Note that the passed RegExp must have the global flag or an error will be thrown.

    Conveniently, this does not throw an error when no matches are found as .matchAll always returns an iterator (vs .match() returning null).


    For this specific example:

    var input = "'Warehouse','Local Release','Local Release DA'";
    var regex = /'(.*?)'/g;
    
    var matches = Array.from(input.matchAll(regex)).map(match => match[1]);
    // [ "Warehouse", "Local Release", "Local Release DA" ]
    
    0 讨论(0)
  • 2020-11-28 11:38

    Not very generic solution since lookbehind isn't supported in Javascript but for given input this regex should work:

    m = input.match(/([^',]+)(?=')/g);
    //=> ["Warehouse", "Local Release", "Local Release DA"]
    
    0 讨论(0)
提交回复
热议问题