Regex difference: (\w+)? and (\w*)

独自空忆成欢 提交于 2020-06-24 08:08:09

问题


Is there any difference between (\w+)? and (\w*) in regex?

It seems the same, doesn't it?


回答1:


(\w+)? and (\w*) both match the same (0..+inf word characters)

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 "".

In Javascript, for example,

/(\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



来源:https://stackoverflow.com/questions/14373310/regex-difference-w-and-w

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!