使用正则表达式检查数字范围
我正在使用正则表达式来验证字符串中的某种格式。该字符串将成为游戏规则。
示例:根据规则,“DX 3”是可以的,但是“DX 14”也可以……我知道如何查看字符串并找到一个或多个“数字”,所以问题是正则表达式将也匹配 34,并且这个数字超出了规则的“范围”...
我是否缺少有关正则表达式的某些内容来执行此操作?或者这根本不可能?
I'm using a regular expression to validate a certain format in a string. This string will become a rule for a game.
Example: "DX 3" is OK according to the rule, but "DX 14" could be OK too... I know how to look at the string and find one or more "numbers", so the problem is that the regex will match 34 too, and this number is out of "range" for the rule...
Am I missing something about the regex to do this? Or is this not possible at all?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不幸的是,没有简单的方法来定义正则表达式中的范围。如果您要使用范围 1-23,您最终会得到如下正则表达式:
说明:
Unfortunately there's no easy way to define ranges in regex. If you are to use the range 1-23 you'll end up with a regex like this:
Explanation:
它不是那么短,而且不灵活。
例如,如果您搜索 1 到 19,您可以搜索“DX 1?[0-9]”,但如果它不以数字边界结束,它很快就会变得丑陋,并且更改规则并不可行灵活的。
在空白处分割字符串,然后使用 x >; 0且x<0 24更好理解,也更灵活。
It is not that short, and not flexible.
If you search for 1 to 19, you can search for "DX 1?[0-9]", for example, but if it doesn't end at a number boundary, it get's ugly pretty soon, and changing the rules is not flexible.
Splitting the String at the blank, and then using x > 0 and x < 24 is better to understand and more flexible.
您可以使用以下格式编写正则表达式来解决您的问题。
假设您的范围是 0-15。
您甚至可以通过附加字符串根据您的范围使其动态。
You can use following format for writing a regular expression solving your problem.
Suppose your range is 0-15.
You can even make it dynamic depending on your range by appending strings.
我还试图找到几分钟的有效范围
[0-60] 为我工作。
我用的是jdk 1.8
I was also trying to find a range of valid range for minutes
[0-60] worked for me.
I am using jdk 1.8 though