大于 x 且小于 y 的数字的正则表达式 [英] Regex for a number greater than x and less than y

查看:109
本文介绍了大于 x 且小于 y 的数字的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在我的网站上创建一个用于捐赠的表单我希望捐赠字段是一个文本框,其值介于 5 到 500 之间,其他货币的值介于 2000 到 200000 之间帮助.

I'm creating a form on my website for donations I want to have the donation field to be a text box with the value of any amount of money between 5 to 500 and for an other currency to be between 2000 and 200000 please help.

推荐答案

这里不要使用正则表达式

有太多方法可以检查 x 是否在一个范围内.这里正则表达式会导致性能问题.

there are too many ways to check ie x is in a range. Regular expression will cause performance problem here.

这是真正的答案

范围为 5 到 500 的正则表达式:

regex for range 5 to 500:

/^(?:[5-9]|(?:[1-9][0-9])|(?:[1-4][0-9][0-9])|(?:500))$/

编辑^2

我不知道为什么正则表达式在这里很重要.但我会解释它是如何工作的.

I do not know why regex is important here. But i will explain how it works.

正则表达式是一种模式匹配语言,我们只能用它来匹配模式.所以,我们必须在其中找到一些模式.
这里的模式是:5-9 或 10-99 或 100-499 和 500.

As regex is a pattern matching language, we can only match pattern with it. So, we have to find some pattern in it.
Here the patterns are: 5-9 or 10-99 or 100-499 and 500.

所以如果我们的正则表达式是 /[5-9]/ 它将匹配我们的第一个.因此 /[1-9][0-9]/, /[1-4][0-9][0-9]//500/ 来了.

So if our regex is /[5-9]/ it will match our first one. Thus /[1-9][0-9]/, /[1-4][0-9][0-9]/ and /500/ came.

但是,我应该多次验证我们的数据吗?
不,您还有另一个选择.
我们将使用管道进行交替检查.
/[5-9]|([1-9][0-9])|([1-4][0-9][0-9])|(500)/

But, should i validate our data multiple time?
No, you have another option.
We will use pipe for alternation check.
/[5-9]|([1-9][0-9])|([1-4][0-9][0-9])|(500)/

实际上这也应该可以正常工作,但我让它们无法捕获.所以我把 ?:

actually this should also work fine but i make them non capuring. So i put ?:

这篇关于大于 x 且小于 y 的数字的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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