Search code examples
javascriptregexmatchnon-greedy

why regular expression .*? only match an empty string in javascript?


/.*?/.exec("abc");//output [""]

I think .*? is non-greedy and it should return a


Solution

  • Well that is expected since .* means 0 or more and by putting ? you make it non-greedy hence it match an empty string.

    If you want to match a then you should use:

     /.+?/.exec("abc");
    

    DIfference is + instead of * which means match 1 or more characters using non-greedy quantifier.