正则表达式:字母后跟数字或数字和字母

10

我在处理一个正则表达式时遇到了一些困难:

G后面跟着1-5个数字

或者G后面跟着4个数字,后面紧跟着一个A-Z的单个字母

可以有人帮忙吗?

有效输入的例子:

G2
G12
G123
G1234
G12345
G1234A

谢谢


6
G(\d{1,5}|\d{4}[A-Z]) 能够匹配所有你的测试用例。 - Phylogenesis
3个回答

16
^[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 中的字母。

测试结果


只有在输入给定示例字符串时,它们被分别输入而不是在同一行中输入,此代码才能正常工作。 - BRAHIM Kamel
2
是的,我只需要将单个字符串与其进行匹配。 - Tommy
{1,5}?(懒惰模式)和[A-Z]?(可选模式)中,您不需要使用? - nhahtdh

3

尝试这个正则表达式

^\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[0-9]{1,5}$|^G[0-9]{4}[A-Z]$" 应该就可以了。 - nhahtdh

0

试试这个:

  G\d{4}[A-Z]|G\d{1,5}

条件语句中的 G 是多余的,可以删除。 - Anirudh Ramanathan
它还匹配了G125A,这个有两个数字太少了。 - Sameer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接