0

I'm trying to make a regex that will match with a number whose sum, it's parity, is even. So 802 (8+0+2) is even, and 902 (9+0+2) is odd. Apparently there is an arithmetic law to do this Regex without counting, or breaking any of Regex's rules. I've made a Regex for even numbers, but not for even parity.

Edit: It's allowed to accept leading zeros, and the number can be any length (obviously smaller than the max size an int can be in most languages)

Thanks!

  • How many digits it should contain ? –  Apr 13 '16 at 17:09
  • Don't think this is possible. I believe the arithmetic you referred in your question has to do with validating an arithmetic expression. Backreferencing is a closest thing that comes to mind, but that is for things like bracket matching, etc... – nurchi Apr 13 '16 at 17:09
  • If it's just two digits then it's simple [`[02468]{2}|[13579]{2}`](https://regex101.com/r/yO9mA4/1). For more digits it's going to be complicated. –  Apr 13 '16 at 17:16
  • It can be a number of any length, and it can contain leading zeros. – Janice Maker Apr 13 '16 at 17:24
  • 1
    Why not simply use programming for sum of all digits in number and check if it's even or odd ? –  Apr 13 '16 at 17:31
  • 1
    @nurchi Think again. It's not impossible, see my answer – Maljam Apr 13 '16 at 17:40
  • If someone asked me how to use a hammer to embed a screw in a board, I'd tell them to sell it and buy a screwdriver. What you're asking with this question is not really an appropriate use of the tool (regex), so I recommend finding a different tool to use. – zzzzBov Apr 13 '16 at 17:45
  • 1
    People, the OP's question is not if there's a "better" way than regex to solve the problem, he is asking if it's doable in regex. Sometimes, in programming, the best justification to use a tool or an algorithm to solve a given problem is "because I want to" or "for the fun of it". – Maljam Apr 13 '16 at 17:48

1 Answers1

0

This is a really tricky one (I'm new to regex), but I just learned that you can use recursion in some flavors of regex.

This is what I came up with:

String regex = "(([02468]*[13579]){2}(?R))|[02468]*$";  

The idea is to use a clever simplification where a number's parity is even only if the number of odd digits is even, because the sum of an even number of odd digits is always even, and the sum of any number of even digits is always even. Explanation:

([02468]*[13579]){2} → 2 odd digits separated by any number of even digits
(?R)                 → Repeat the whole regex on the string after match
|                    → OR
[02468]*$            → the rest of String is 0 or more even digits

EDIT
Recursion only makes the notation simpler, but it's still possible without recursion (some languages like Java do not have recursion implemented), the idea is same:

String regex = "(([02468]*[13579]){2})*[02468]*$"
Maljam
  • 6,244
  • 3
  • 17
  • 30