Regex to extract substring, returning 2 results for some reason

后端 未结 5 1392
情话喂你
情话喂你 2020-11-28 08:13

I need to do a lot of regex things in javascript but am having some issues with the syntax and I can\'t seem to find a definitive resource on this.. for some reason when I d

5条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 08:17

    I've just had the same problem.

    You only get the text twice in your result if you include a match group (in brackets) and the 'g' (global) modifier. The first item always is the first result, normally OK when using match(reg) on a short string, however when using a construct like:

    while ((result = reg.exec(string)) !== null){
        console.log(result);
    }
    

    the results are a little different.

    Try the following code:

    var regEx = new RegExp('([0-9]+ (cat|fish))','g'), sampleString="1 cat and 2 fish";
    var result = sample_string.match(regEx);
    console.log(JSON.stringify(result));
    // ["1 cat","2 fish"]
    
    var reg = new RegExp('[0-9]+ (cat|fish)','g'), sampleString="1 cat and 2 fish";
    while ((result = reg.exec(sampleString)) !== null) {
        console.dir(JSON.stringify(result))
    };
    // '["1 cat","cat"]'
    // '["2 fish","fish"]'
    
    var reg = new RegExp('([0-9]+ (cat|fish))','g'), sampleString="1 cat and 2 fish";
    while ((result = reg.exec(sampleString)) !== null){
        console.dir(JSON.stringify(result))
    };
    // '["1 cat","1 cat","cat"]'
    // '["2 fish","2 fish","fish"]'
    

    (tested on recent V8 - Chrome, Node.js)

    The best answer is currently a comment which I can't upvote, so credit to @Mic.

提交回复
热议问题