Regex Pattern Differences - “*” and “+”

耗尽温柔 提交于 2019-12-13 10:28:38

问题


I am trying to replace " on inch i.e. 12" wall would become 12 inch wall

I have 2 patterns working:

/\b([0-9]+)"/ -> preg_replace('/\b([0-9]+)"/', '$1 inch ', $string)

and

/\b([0-9]*)"/ -> preg_replace('/\b([0-9]*)"/', '$1 inch ', $string)

what is a difference between them then, why + and * works same way here ?

cheers, /Marcin


回答1:


The + means find the previous character/group 1 or more times.

The * means find the previous character/group any amount of times (0-infinity)




回答2:


/\b([0-9]+)"/ requires that there is at least one digit between the word boundary and the ", whereas /\b([0-9]*)"/ also accepts zero digits. So the first does not match a space followed by " and the second does.

If you want to mach both new 15 " tv and new 15" tv you need to match against a space character that may or may not be present:

/\b([0-9]+)\s?"/

This matches a word boundary, followed by a sequence (on or more) numbers, optionally followed by one space (or tab), followed by a ". I presume that's what you are looking for. If not, you should first define strings that must match and strings that may not match.



来源:https://stackoverflow.com/questions/6166996/regex-pattern-differences-and

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