It’s very easy to check a decimal number is divisible by three using a simple DFA with 3 states.
A regex, therefor, is possible, but not too pretty (source):
(?:[0369]| [147](?:[0369]*[147][0369]*[258])*(?:[0369]*[258]|[0369]*[147][0369]*[147])| [258](?:[0369]*[258][0369]*[147])*(?:[0369]*[147]|[0369]*[258][0369]*[258]) )*
Example: http://www.rubular.com/r/ZcRDblHg8M
Here’s another approach, using .Net’s stacks as a simple counter:
\b
(?> # No regrets - don't backtrack on if/else decisions.
[0369] # = 0 (mod 3)
|
[147] # = 1 (mod 3)
(?: # if possible pop 2, else push 1
(?<-Sum>){2}|(?<Sum>)
)
|
[258] # = 2 (mod 3)
(?: # if possible pop 1, else push 2
(?<-Sum>)|(?<Sum>){2}
)
)+
\b
(?(Sum)(?!)) # Assert nothing's left in the stack
Why? Well, I was bored while I shaved. Luckily, this regex is simple enough for Mono. Working example: http://ideone.com/Yp6Ti (ok, maybe not, mono is missing 111222)
Advertisement