pranab
pranab

Reputation: 155

Regex format for validation

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

Upvotes: 3

Views: 95

Answers (3)

CinCout
CinCout

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.

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

Upvotes: 3

Tim Biegeleisen
Tim Biegeleisen

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

Emma
Emma

Reputation: 27723

For validation, maybe limiting the number of X would be fine, such as with:

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

Demo 1

or:

^(?:\dX{5}|\d{2}X{4}|\d{3}X{3}|\d{4}X{2}|\d{5}X|\d{6})$

Demo 2

Upvotes: 0

Related Questions