Home > Enterprise >  Regular expression c# for last 2 digits
Regular expression c# for last 2 digits

Time:01-18

I have a text box with only numbers, my regex is:

^[1-9][0-9][0-9][48,88,51,01]$

I want only numbers ending with that 2 digits (48,88,51,01) How I can validate this, I'm not good with regular expresions :(

CodePudding user response:

To match 6 numbers, the first 4 can be whatever, and the group of 2 using C#, and ending on one of 48, 88, 51, 01 you can make use of a character class but with a different notation.

Then you can make use of a non capture group for the alternatives.

^[0-9]{4}(?:[48]8|[50]1)$

See a regex101 demo.

Or if the first digit should be 1-9:

^[1-9][0-9]{3}(?:[48]8|[50]1)$

See another regex demo.

CodePudding user response:

Here you have another approach:

\d*(48|88|51|01)$

This regular expression first uses the "\d*" pattern to match zero or more digits, then the pipe "|" operator to match either 48, 88, 51, or 01 at the end of the string, indicated by the "$" character.

CodePudding user response:

You want to use a non-capturing group (?:...) with the or operator:

^[1-9][0-9][0-9](?:48|88|51|01)$
  • Related