问题
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