问题
I want a PHP regular expression that must start from 1 to 5 lower case characters, followed by an optional underscore, and then followed by 0 to 5 numbers/digits.
This is my code: '/[a-z][_][0-9]/'
回答1:
You're close. You need range and optional sigils:
/[a-z]{1,5}_?[0-9]{0,5}/
The expression {n,m}
following a character class means the class must match at least n
times and at most m
times.
The expression ?
following a character means the character must match 0 or 1 times. It's equivalent to {0,1}
, just shorter.
If this doesn't work for your subject strings, please post some example matches and non-matches.
来源:https://stackoverflow.com/questions/59331689/php-regular-expression-with-optional-underscore-and-number