Reputation: 155
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:
So I need a regex format for
Upvotes: 3
Views: 95
Reputation: 9619
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
.
For case-insensitivity, use the /i
flag:
^[0-9]{1,6}X*$ /gmi
Alternatively, you can also use a character set with both small and capital letters:
^[0-9]{1,6}[Xx]*$ /gm
A positive lookahead will restrict the maximum length as desired:
^(?=.{1,6}$)[0-9]*[Xx]*$ /gm
Upvotes: 3
Reputation: 520878
Try the following pattern:
^(?=.{1,6}$)[0-9]{1,6}X*$
Here is an explanation of the pattern:
^ from the start of the string
(?=.{1,6}$) assert that the total length is at least 1 and at most 6
[0-9] then match 1 to 6 digits
X* followed by optional X
$ end of string
Upvotes: 3