Regex plus vs star difference?

2018-12-31 19:20发布

What is the difference between:

(.+?)

and

(.*?)

when I use it in my php preg_match regex?

标签: php regex
9条回答
美炸的是我
2楼-- · 2018-12-31 19:37

A + matches one or more instances of the preceding pattern. A * matches zero or more instances of the preceding pattern.

So basically, if you use a + there must be at least one instance of the pattern, if you use * it will still match if there are no instances of it.

查看更多
姐姐魅力值爆表
3楼-- · 2018-12-31 19:40

+ matches at least one character

* matches any number (including 0) of characters

The ? indicates a lazy expression, so it will match as few characters as possible.

查看更多
冷夜・残月
4楼-- · 2018-12-31 19:40

A star is very similar to a plus, the only difference is that while the plus matches 1 or more of the preceeding character/group, the start matches 0 or more.

查看更多
无与为乐者.
5楼-- · 2018-12-31 19:47

Consider below is the string to match.

ab

The pattern (ab.*) will return a match for capture group with result of ab

While the pattern (ab.+) will not match and not returning anything.

But if you change the string to following, it will return aba for pattern (ab.+)

aba
查看更多
何处买醉
6楼-- · 2018-12-31 19:50

+ is minimal one, * can be zero as well.

查看更多
栀子花@的思念
7楼-- · 2018-12-31 19:52

I think the previous answers fail to highlight a simple example:

for example we have an array:

numbers = [5, 15]

The following regex expression ^[0-9]+ matches: 15 only. However, ^[0-9]* matches both 5 and 15. The difference is that the + operator requires at least one duplicate of the preceding regex expression

查看更多
登录 后发表回答