简体   繁体   English

为什么使用正则表达式。*? 只匹配JavaScript中的空字符串?

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

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

I think .*? 我认为.*? is non-greedy and it should return a 是非贪婪的,它应该返回a

Well that is expected since .* means 0 or more and by putting ? 好吧,这是可以预期的,因为.*表示0或更大,并放置? you make it non-greedy hence it match an empty string. 您将其设为非贪婪,因此它匹配一个空字符串。

If you want to match a then you should use: 如果要匹配a ,则应使用:

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

DIfference is + instead of * which means match 1 or more characters using non-greedy quantifier. 差异是+而非* ,表示使用非贪婪量词匹配1个或多个字符。

通过使用*代替eg +您允许将空字符串作为非贪婪选项进行匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM