Regular expression help in PHP (8 hexadecimal characters followed by an underscore)

社会主义新天地 提交于 2019-12-12 13:09:12

问题


I want to validate if my input consists starting with 8 hexadecimal characters followed by a underscore, followed by any number of charters with any value.

Im currently using the following regular expression:

preg_match('/^[0-9A-Fa-f]{8}_*/', $value);

But this expression does not fulfill my needs because it behaves the following way

Result:

1A345678            (true)
1A345678_add        (true)
1234567890          (true)
ABSDBASDB           (false)

Expected result:

1A345678            (false)
1A345678_add        (true)
1234567890          (false)
ABSDBASDB           (false)

What is wrong with my regular expression?


回答1:


You are just missing a .

preg_match('/^[0-9A-Fa-f]{8}_.*/', $value);

With _* you were matching for 0 or more underscores. * is a quantifier that repeats the preceding character or group 0 or more times. Therefor it matches also strings without the underscore at the end (0 repetitions of the _)

. is a regex special character, that matches any character (by default except newlines)




回答2:


Try removing the *:

preg_match('/^[0-9A-Fa-f]{8}_/', $value);



回答3:


replace * with .* after underscore

preg_match('/^[0-9A-Fa-f]{8}_.*/', $value);


来源:https://stackoverflow.com/questions/15221420/regular-expression-help-in-php-8-hexadecimal-characters-followed-by-an-undersco

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