我在处理一个正则表达式时遇到了一些困难:
G后面跟着1-5个数字
或者G后面跟着4个数字,后面紧跟着一个A-Z的单个字母
可以有人帮忙吗?
有效输入的例子:
G2
G12
G123
G1234
G12345
G1234A
谢谢
^[G][0-9]{1,5}?$|^[G][0-9]{4}[A-Z]?$
^[G]
表示以 G 开头
[0-9]{1,5}
表示接下来的 1 到 5 个字符是数字
[0-9]{4}
表示接下来的 4 个字符是数字
[A-Z]
表示最后一个字符必须是 A - Z 中的字母。
{1,5}?
(懒惰模式)和[A-Z]?
(可选模式)中,您不需要使用?
。 - nhahtdh尝试这个正则表达式
^\b[G][0-9]{1,5}?$|^[G][0-9]{4}[A-Z]?$
操作者:
正则表达式解释
NODE EXPLANATION
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
\b the boundary between a word char (\w) and
something that is not a word char
--------------------------------------------------------------------------------
[G] any character of: 'G'
--------------------------------------------------------------------------------
[0-9]{1,5}? any character of: '0' to '9' (between 1
and 5 times (matching the least amount
possible))
--------------------------------------------------------------------------------
$ before an optional \n, and the end of the
string
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
[G] any character of: 'G'
--------------------------------------------------------------------------------
[0-9]{4} any character of: '0' to '9' (4 times)
--------------------------------------------------------------------------------
[A-Z]? any character of: 'A' to 'Z' (optional
(matching the most amount possible))
--------------------------------------------------------------------------------
$ before an optional \n, and the end of the
string
试试这个:
G\d{4}[A-Z]|G\d{1,5}
G(\d{1,5}|\d{4}[A-Z])
能够匹配所有你的测试用例。 - Phylogenesis