Home > Blockchain >  Write regex patterns for matching single digit or double digit where tens place value is 2 or 4
Write regex patterns for matching single digit or double digit where tens place value is 2 or 4

Time:04-13

Below is my regex for matching 2 digit where tens place value is 2 or 3 and it is working fine.

^(?=[2,4])\d{1,2}$

As soon as I add the regex for matching single digit in above regex , It started matching single digit and as well all 2 digit number.

^(?=\d|[2,4])\d{1,2}$

I want below sample input to be matched.

0
1
2 
3
24 
44
48
29
28

Below not to be matched.

99
11
33
55
77

Also It will great help if I would get to know why my regex is not working.

CodePudding user response:

Try this: ^(\d|[2,4]\d)$

Test regex here: https://regex101.com/r/aZo7fK/1

^(\d|[2,4]\d)$

^            matches the start of string
(\d|[2,4]\d) matches either a single digit(0-9) or a two digit number which starts with either 2 or 4
$            matches the end of the string
  • This matches either a single digit(0-9) number or a two digit number which starts with either 2 or 4.

CodePudding user response:

You get a difference in matches as the positive lookahead asserts that there must be to the right what you specify. In there first pattern that is either 2 4 or , and in the second case just a single digit.

You don't have a comma in your example data, so in that case you can match an optional 2 or 4 using just [24]? followed by a digit without any lookarounds.

^[24]?\d$

See a regex demo.

CodePudding user response:

I suggest

^[2,4]?[0-9]$

pattern; where

^      - anchor, start of the text
[2,4]? - optional 2 or 4 digit for tens
[0-9]  - mandatory digit 0..9 for units
$      - anchor, end of the text

Edit: Now, let's have a look at your current patterns; the first is

^(?=[2,4])\d{1,2}$

Here

(?=[2,4]) - look ahead for 2 or 4
\d{1,2}   - one or two digits

as we can see 3 doesn't match: look ahead fails to find 2 or 4. As for your second attempt

^(?=\d|[2,4])\d{1,2}$

pattern, where

 (?=\d|[2,4]) - look ahead for ANY digit (note, that |[2,4] is redundant)
 \d{1,2}      - one or two digits

the pattern matches too many texts; technically it matches any one or two digit numbers, e.g. for:

 79

we have

 (?=\d|[2,4]) - look ahead - succeeds with 7
 \d{1,2}      - one or two digits - succeeds with 79
  • Related