user1950349
user1950349

Reputation: 5146

Make a regex to validate string in particular format

I am trying to write a regex that matches my string with below format:

I came up with below regex but having issues coming up for my third point. This line (1[9][0-9]{2}|2019) looks wrong and it doesn't work for string UYT20121000X:

^(([A-Z])(?!\2)([A-Z])(?!\2|\3)[A-Z])(1[9][0-9]{2}|2019)(10{1,3}|[25]00?)([A-Z])$

After using above regex I will extract the number which matches my fourth point.

Upvotes: 1

Views: 62

Answers (3)

The fourth bird
The fourth bird

Reputation: 163197

You could use (?:19\d{2}|20[01]\d) to match the range from 1900-2019.

It matches from 1900 till 1999 or from 2000 till 2019

The updated pattern could look like

^(([A-Z])(?!\2)([A-Z])(?!\2|\3)[A-Z])(19\d{2}|20[01]\d)(10{1,3}|[25]00?)([A-Z])$

Regex demo

Upvotes: 1

Bohemian
Bohemian

Reputation: 424953

Your regex only matches exactly 2019 from this century, not the range 2000-2019.

To match the range 1900-2019:

(19\d\d|20[01]\d)

Putting in your regex (and removing unnecessary groups):

^([A-Z])(?!\1)([A-Z])(?!\1|\2)[A-Z](19\d\d|20[01]\d)(10{1,3}|[25]00?)([A-Z])$

Upvotes: 1

mankowitz
mankowitz

Reputation: 2031

Try ^(([A-Z])(?!\2)([A-Z])(?!\2|\3)[A-Z])(19[0-9]{2}|20[01][0-9])(10{1,3}|[25]00?)([A-Z])$

The format you want is either 19aa or 20ba

where a is any digit and b is either 0 or 1

Upvotes: 1

Related Questions