Home > OS >  Regex for matching 1 character a uppercase letter, 2nd could be letter / number, rest numbers
Regex for matching 1 character a uppercase letter, 2nd could be letter / number, rest numbers

Time:12-09

I wrote a regular expression test a certain type of string It works well but some part of me says I am not sure if there are exception that invalidates it.

type of string I need to validate are these.

'GX2480', 'H03667', 'HQ2999'

regular expression I wrote is "^[A-Z]{0,1}[A-Z0-9]{0,1}[0-9]{0,4}$"

Here is the JSBin in case anyone wants to experiment.

https://jsbin.com/yikuqonepu/edit?html,js,console

CodePudding user response:

You can test your regular expression online. The following link is one of the examples.

And your regex accepts string like '', '0', 'H0' because you accept the {0} number of characters and numbers. I would change the regex into this:

"^[A-Z]{1}[A-Z0-9]{1}[0-9]{4}$"

CodePudding user response:

"^[A-Z]{0,1}[A-Z0-9]{0,1}[0-9]{0,4}$" would also match an input of only numbers or an empty input since everything is optional.

If you want to force your input to start with a letter, don't make it optional: "^[A-Z][A-Z0-9]?[0-9]{0,4}$"

Valid inputs:

  • "A"
  • "AB"
  • "A1"
  • "AB1"
  • "AB1234"
  • "A12345"

Invalid inputs:

  • ""
  • "ABC"
  • "AB12345"
  • "AB12C"
  • "1"
  • "123"

If the real question is how to match input strings of exactly length 6, the first character always being a letter, the last 4 characters always digits and the second character lettor or digit, then the regex would be:

^[A-Z][A-Z0-9][0-9]{4}$

Valid inputs:

  • "AB1234"
  • "A12345"

Invalid inputs:

  • "A"
  • "AB"
  • "A1"
  • "AB1"
  • ""
  • "ABC"
  • "AB12345"
  • "AB12C"
  • "AB123C"
  • "ABC123"
  • "1"
  • "123"

Alternatively, it could be formulated as follows, perhaps this is more explicit of the two different forms of inputs you allow:

^([A-Z]{2}[0-9]{4}|[A-Z][0-9]{5})$
  • Related