Why is this regex failing when adding anchors?

左心房为你撑大大i 提交于 2019-12-10 23:38:03

问题


This is a match:

preg_match('/[a-bA-B0-9]+/', 'username')

But this is not:

preg_match('/^[a-bA-B0-9]+$/', 'username')

Why is that?


回答1:


Are you testing the actual literal 'username'?

/[a-bA-B0-9]+/ will test the existence of a,b,A,B,0,1,2,3,4,5,6,7,8,9 anywhere in the string. So it will match abBa854Abba32, and it will match sjfsgfafnvesv.

/^[a-bA-B0-9]+$/ will test that the enitre string is made of a,b,A,B,0,1,2,3,4,5,6,7,8,9. So it will match abBa854Abba32, and it will not match sjfsgfafnvesv.

Perhaps you meant /^[a-zA-Z0-9]+$/.




回答2:


The second does not match because you have told the regex to match a sequence that starts with one of those items in the character class. The first letter of your string is "u", and there is no "u" in your character class [a-bA-B0-9].




回答3:


From here

You can see that it only matches a:

Results

1 match was found:

Array ( [0] => a )



来源:https://stackoverflow.com/questions/10134512/why-is-this-regex-failing-when-adding-anchors

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