简体   繁体   English

正则表达式的区别:(\\ w +)? 和(\\ w *)

[英]Regex difference: (\w+)? and (\w*)

Is there any difference between (\\w+)? (\\w+)?之间有什么区别(\\w+)? and (\\w*) in regex? 正则表达式中的(\\w*)

It seems the same, doesn't it? 看来是一样的,不是吗?

(\\w+)? and (\\w*) both match the same (0..+inf word characters) (\\w*)都匹配相同(0 .. + inf字符)

However, there is a slight difference: 但是,有一点点差异:

In the first case, if this part of the regex matches "" , the capturing group is absent. 在第一种情况下,如果正则表达式的这部分匹配"" ,则捕获组不存在。 In the second case, it is empty. 在第二种情况下,它是空的。 In some languages, the former manifests as a null while the latter should always be "" . 在某些语言中,前者表示为null而后者应始终为""

In Javascript, for example, 例如,在Javascript中,

/(\w*)/.exec("")  // ["", ""]
/(\w+)?/.exec("") // ["", undefined]

In PHP ( preg_match ), in the former case, the corresponding key is simply absent in the matches array: http://3v4l.org/DB6p3#v430 在PHP( preg_match )中,在前一种情况下,匹配数组中根本没有相应的键:http: //3v4l.org/DB6p3#v430

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

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