Regex with at least three even digits and odd length

968 Views Asked by At

As the title said, I need to make a regex for a number with at least three even digits and odd length. As an example, the number 248 should match. Thank you!

2

There are 2 best solutions below

0
On BEST ANSWER

Let $e$ denote any even digit and $o$ any odd digit. Let

$$E=\big((e+o)(e+o)\big)^*$$

and

$$O=(e+o)E\,.$$

Then the expression

$$\begin{align*} &E(eee+eeEe+eEee+eEeEe+eOeOe)E\\ &\qquad+O(eee+eeEe+eEee+eEeEe+eOeOe)O\\ &\qquad+E(eeOe+eOee+eOeEe+eEeOe)O\\ &\qquad+O(eeOe+eOee+eOeEe+eEeOe)E \end{align*}$$

should do the trick.

0
On

If you are allowed to create capturing and non-capturing groups (e.g. python) then it is possible to reduce the regex by having an AND operation performed rather than having to list all combinations like in Brian's answer.

(?=oddcount)(?:evendigits)

oddcount = ^[0-9]([0-9][0-9])+$

evendigits = ^[0-9]*[02468][0-9]*[02468][0-9]*[02468][0-9]*$

Note: I enclosed expression inside ^...$ to match the whole string, not just some part of it.

Test it here: https://regex101.com/r/dgbngY/1