如何编写正则表达式来匹配数字范围? [英] How to write regex to match number ranges?

查看:39
本文介绍了如何编写正则表达式来匹配数字范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 asp.net RegularExpressionValidator 检查多行文本框上的输入.我几乎拥有它,但我一定错过了一些东西.它应该是这样的:

I am using the asp.net RegularExpressionValidator to check for input on a multiline textbox. I ALMOST have it, but I must be missing something. This is how it SHOULD be:

1 => valid

1-10 => valid

1-10,45,50 => valid

1 10 45 50 => valid

111 => INVALID

然而,111 又回来了 Valid

However, 111 is coming back Valid

这是我正在使用的正则表达式:"(([0-9]{1,2})(,|\s|-)?)*" 它适用于除111,它表示有效.我知道为什么它认为它是有效的,我只是不知道如何使它无效.

Here is the regex I am using: "(([0-9]{1,2})(,|\s|-)?)*" and it works for everything but 111, where it is saying valid. I know why it thinks it's valid, I just don't know how to make that invalid.

推荐答案

不要让分隔符可选,那么你将匹配 number-nothing-number,因此匹配 111,而是执行以下操作:

Don't make the seperator optional, then you will match number-nothing-number, and therefore match 111, instead do something like:

"[0-9]{1,2}([-,\s][0-9]{1,2})*"

为清楚起见:如果您的正则表达式引擎不匹配整个字符串,则需要在开头添加 ^$ 在正则表达式的末尾.

edit: for clarity: If your regex engine does not match the whole string, you need to add ^ at the start, and $ at the end of the regex.

这篇关于如何编写正则表达式来匹配数字范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆