简体   繁体   English

正则表达式匹配1或2个字母,后跟1或2个数字

[英]Regex to match 1 or 2 alphabets followed by 1 or 2 digits

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. 我需要形成正则表达式的帮助,以检查输入的字符串是否仅是模式1或2个字母(可以是小写或大写),然后是1或2个数字。 Valid strings would be d1,d15,ha1,ha20 so on. 有效字符串为d1,d15,ha1,ha20,依此类推。

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-zA-Z]是与任何字母匹配的字符类, \\d等效于[0-9]并且与任何数字匹配,并且{1,2}意思是“将前一个元素重复1或2次”。

\\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). \\A\\z是锚点,它们分别仅在字符串的开头和结尾匹配(它们不匹配任何字符,它们只需要在字符串的开头或结尾进行匹配即可)。

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. 您通常还会看到锚点^$ ,我使用了\\A\\z因为$会在字符串末尾的换行符之前匹配,并且可以通过options修改其行为,而\\z始终表示末尾字符串。

The following page gives a nice summary on regular expression syntax: 下一页对正则表达式语法进行了很好的总结:
http://www.regular-expressions.info/reference.html http://www.regular-expressions.info/reference.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM