Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex format for validation

Tags:

regex

I am trying to validate below format in regex but I am not successful.

I have tried below regex

"^[0-9]{1,6}X{1}$"

"^[0-9]{1,6}X$"

It doesn't satisfy all conditions.

Required Format:

  1. 12345 (only number is correct)
  2. 2753XX (number with X is correct but X must be after number)
  3. 542XXX45 (this format is not correct because X is between the number).
  4. 4654abc ( this format is not correct because it is alpha numeric)

So I need a regex format for

  1. String starts with number
  2. String starts with number and end with X only
  3. Max length of the string is 6 including X
like image 999
pranab Avatar asked May 31 '26 22:05

pranab


1 Answers

You missed making the X optional. Do this:

^[0-9]{1,6}X*$ /gm

This will mean text starting with one to six digits, ending in zero or more X.

Demo

For case-insensitivity, use the /i flag:

^[0-9]{1,6}X*$ /gmi

Demo

Alternatively, you can also use a character set with both small and capital letters:

^[0-9]{1,6}[Xx]*$ /gm

Demo

A positive lookahead will restrict the maximum length as desired:

^(?=.{1,6}$)[0-9]*[Xx]*$ /gm

Demo

like image 126
CinCout Avatar answered Jun 02 '26 19:06

CinCout