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!
Asked
Active
Viewed 967 times
0
-
How about the number $21418$? – JMoravitz Jan 18 '21 at 19:27
-
yes, this should match – Carl J. Jan 18 '21 at 19:28
2 Answers
1
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.
Brian M. Scott
- 616,228
0
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+$
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
zwim
- 28,563