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

时间:2014-02-05 10:46:10

标签: c# asp.net regex

我对以下正则表达式有一些困难:

G后跟1-5个数字

或G后跟4个数字,后跟单个字母A-Z

有人可以帮忙吗?

e.g。有效的条目是:

G2
G12
G123
G1234
G12345
G1234A

由于

3 个答案:

答案 0 :(得分:8)

^[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之间的字母。

Test results

答案 1 :(得分:0)

试试这个: -

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

答案 2 :(得分:0)

试试这个正则表达式

^\b[G][0-9]{1,5}?$|^[G][0-9]{4}[A-Z]?$

REGEX DEMO

OP:

enter image description here

正则表达式解释

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