Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression Letter followed by numbers or numbers and a letter

Tags:

c#

regex

asp.net

I am having some difficulty with the following for a regular expression:

G followed by 1-5 numbers

or G followed by 4 numbers followed by a single letter A-Z

Could someone please assist?

e.g. of valid entries would be:

G2
G12
G123
G1234
G12345
G1234A

Thanks

like image 620
Tommy Avatar asked Feb 05 '14 10:02

Tommy


2 Answers

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

^[G] means starts with G [0-9]{1,5} means next 1 to 5 letters are numeric [0-9]{4} means next 4 letters are numeric [A-Z] means last character must be a letter between A -Z.

Test results

like image 197
Sameer Avatar answered Nov 15 '22 18:11

Sameer


Try this Regex

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

REGEX DEMO

OP:

enter image description here

Regex Explanation

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
like image 20
Vignesh Kumar A Avatar answered Nov 15 '22 19:11

Vignesh Kumar A