I need help forming a regular expression to check if the input string is ONLY of the pattern 1 or 2 alphabets (can be lower or uppercase) followed by 1 or 2 digits. Valid strings would be d1,d15,ha1,ha20 so on.
The following should do what you want:
\A[a-zA-Z]{1,2}\d{1,2}\z
[a-zA-Z]
is a character class that matches any letter, \\d
is equivalent to [0-9]
and matches any digit, and {1,2}
means "repeat the previous element 1 or 2 times".
\\A
and \\z
are anchors, and they only match at the beginning and end of a string respectively (they don't match any characters, they just require the string to start or end at them to allow a match).
You will also commonly see the anchors ^
and $
, I used \\A
and \\z
because $
will match just before a newline at the end of the string and can have its behavior modified by options, whereas \\z
always means the very end of the string.
The following page gives a nice summary on regular expression syntax:
http://www.regular-expressions.info/reference.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.