Reputation: 1635
I have to find regular expression defining any even number, with at least one "5" digit inside. I've been thinking about:
(0+1+2+3+4+5+6+7+8+9)* 5 (0+1+2+3+4+5+6+7+8+9)* (0+2+4+6+8)
Will this work? Is there a way to make it shorter?
Well, I'm not sure if this is the right website to post this question...but the tag exists :P
Upvotes: 0
Views: 82
Reputation: 13616
Your regexp looks good. I don't think you can make it shorter (if we are speaking about theoretical regexps; real programming languages have shortcuts like [0-9]
or \d
for any digit).
As pointed out by others your regexp will also match numbers starting from any number of zeroes. If you don't want this, you will of course try to match the first digit with (1|2|3|4|5|6|7|8|9)
, but now you've got a special case: what if the first digit is 5
? So you'll have to add more branches.
Your regexp is fine, but I think that making it match only numbers without leading zeroes is a good exercise and you should try it anyway, even if your task doesn't require this.
Here is a general advice. Problems requiring you to create regular expressions are best wil help of Test-driven development. That is, before trying to write the regexp you create a set of tests for it. It has a number of benefits:
Upvotes: 3