Home > Back-end >  regex - conditional check for 2nd digit based on first digit
regex - conditional check for 2nd digit based on first digit

Time:07-04

I am looking up for a regular expression that checks the following:

  • first digit can be 0 or 1 or 2 [012]
  • if the first digit is 0, then second digit should be odd number [1379]
  • if the first digit is 1, then second digit should be 5 and 10
  • if the first digit is 2, then second digit should be even number [02468]

I stumbled upon look ahead and look behind. I could succeed in getting only one condition success, using this expression.

/[0-2](?<=0)[1379]/

The above checks, if digit is 0, then 2nd digit is odd.

I am unable to get the other two conditions to match. Any help?

CodePudding user response:

The pattern [0-2](?<=0)[1379] looks like you want to use a conditional like "if the value is 0 to the left in the range of 0-2, then match one of [1379]"

But if you assert a 0 on the left, you are not matching it but asserting it.

You could use a capture group in the lookbehind assertion and then combining that with a conditional, but also combining that with an alternation will get multiple capture group numbers which you would have to eventually combine those getting the matches and that would be unnecessarily complex.

Asserting the digits to the left and capture in groups:

(?<=(0)|(1)|(2))(?(1)([1379]))(?(2)(5|10))(?(3)([02468]))

Regex demo

Or without the lookbehind, matching the groups

(?:(0)|(1)|(2))(?(1)([1379]))(?(2)(5|10))(?(3)([02468]))

Regex demo


But it is much easier you specify the alternatives that you want to allow to match without looking to the left of use an if clause at all:

\b(?:0[1379]|1(?:5|10)|2[02468])\b

See the regex demo

  • Related