Mopparthy Ravindranath
Mopparthy Ravindranath

Reputation: 3308

regex - conditional check for 2nd digit based on first digit

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

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?

Upvotes: 1

Views: 497

Answers (1)

The fourth bird
The fourth bird

Reputation: 163372

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

Upvotes: 2

Related Questions