[英]Match even numbers containing at least one “5” digit
I have to find regular expression defining any even number, with at least one "5" digit inside. 我必须找到定义任何偶数且包含至少一个“ 5”数字的正则表达式。 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 好吧,我不确定这是否是发布此问题的合适网站...但是标记存在:P
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). 我认为您不能缩短它的时间(如果我们谈论的是理论上的正则表达式;实际的编程语言会使用[0-9]
或\\d
这样的快捷键来表示任何数字)。
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
? 如果您不想这样做,您当然会尝试将第一个数字与(1|2|3|4|5|6|7|8|9)
匹配,但是现在您有一个特殊情况:如果第一个数字是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: 它具有许多优点:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.