Regular expression to limit length to 8 chars

Viewed 222

I need a regular expression to match a string as follows:

  • Length 8
  • Start with number 4 or 6
  • The remaining characters can be 7 numbers OR 6 numbers with an x at the end

e.g.

  • 41234568
  • 4123456x
  • 4234234X
  • 62432434
  • 6243243x

I have the following but it doesn't work for 62432434 or 41234568

^((4|6)([0-9]{6,7})(X|x))$  
3 Answers

You can use

^[46][0-9]{6}[Xx0-9]$
^[46]\d{6}[Xx\d]$

See the regex demo

Details:

  • ^ - start of string
  • [46] - 4 or 6
  • [0-9]{6} - six digits
  • [Xx0-9] - x, X or a digit
  • $ - end of string.

See the regex graph:

enter image description here

Could you please try following, written and tested with shown samples. Online regex Online regex demo

^[46](?:(?:\d{7})|(?:\d{6}[xX]))$

Explanation:

^[46]         ##Starting with either 4 or 6.
(?:           ##Starting non-capturing group here.
(?:\d{7})     ##Checking condition if either 7 digits.
|
(?:\d{6}[xX]) ##checking if 6 digits with x OR X coming
)$            ##Using $ to mention end of line.

So, essentially you need to brake this down into two statements.

First, you want a 4 or a 6, followed by 7 numbers:

    ^(4|6)([0-9]{7}$)

Then, you want a 4 or a 6, followed by 6 numbers and ending with an X or x:

    ^(4|6)([0-9]{6}(X|x)$)

So, you can combine those as an OR i.e. | in regex:

    ^(4|6)(([0-9]{7}$)|([0-9]{6}(X|x)$))

That should do it. https://regex101.com/r/QQzUOT/1

Related