JavaScript regular expression with global match help needed

后端 未结 3 720
孤独总比滥情好
孤独总比滥情好 2021-01-13 15:45

I\'m new to JavaScript and have a question about regular expressions. I have the following code:

var patt3=new RegExp(/(July|August)\\s+\\d{1,2}(\\s|,)\\d{4}         


        
相关标签:
3条回答
  • 2021-01-13 16:16

    g only matches all occurrences of the entire pattern. It is not analogous to matching groups like PHP's preg_match_all. Without g, it only matches the first occurrence of the pattern (matches[0]) and all matched groups are the other array elements.

    If you wanted to get nested matches as well, you can use the concepts described by John Resig to do so:

    str3.replace(patt3, function () {
        //This is the first captured group in all matches iterated over
        console.log(arguments[1]);
    });
    
    0 讨论(0)
  • 2021-01-13 16:26

    Quoting the docs on String.match:

    If the regular expression does not include the g flag, returns the same result as regexp.exec(string).

    If the regular expression includes the g flag, the method returns an Array containing all matches. If there were no matches, the method returns null.

    In the second example, the first element of the array is the match, while the others are capturing groups. With g, each element would be a different match.

    0 讨论(0)
  • 2021-01-13 16:28

    The crucial difference is that the string.match method is defined to have a different behavior if the regex patter is global or not.

    If the pattern is global, an array with all the matches. In your case you there is only one match but you can see the difference with an example like

    let matches = "aaaa".match(/a(a)/g); 
    console.log(matches) // returns ["aa", "aa"]

    If the pattern is not global, however, the method return an array corresponding to the first match found. The array contains the full matched string in the first position and the captures in the other positions. The captures are the bits of the regex delimited by parenthesis. Again, you can see the difference with that example:

    "aaaa".match(/a(a)/g); // returns ["aa", "a"]
    

    Finally, I would just like to point out some minor issues with your code.

    First of all, you don't need to use the new Regexp constructor here. Just use the regex literal directly

    var patt3 = /(July|August)\s+\d{1,2}(\s|,)\d{4}/g
    

    Secondly, don't blindly "toString" things. In your case you are applying that method to an array and that's why you get your weird results.

    Finally, learn to use the developer tools, including the debugger and console.log. Its much better than abusing document.write and alert in terms of expressiveness and productivity.

    console.write(match3)
    
    0 讨论(0)
提交回复
热议问题