了解数字范围的正则表达式 [英] Understanding Regular Expression for Number Range

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

问题描述

我正在尝试构建一些正则表达式来验证某些文本框控件.我已经进行了一些研究和测试,但无法使这一工作正常进行.我尝试为其创建正则表达式的示例如下:

I'm trying to build up some regular expressions to validate some textbox controls. I have done some research and testing but cannot get this one working. Examples of what i am trying to create regular expressions for are as follows:

  1. 范围0-45,小数点后0位
  2. 范围0-20,小数点后2位
  3. 范围16-65,小数点后0位
  4. 范围0-99,小数点后2位
  5. 范围0-1500000,小数点后0位
  6. 范围0-200,小数点后1位

我分别用1和5用过

([0-9]|[0-9]\d|45)$  
([0-9]|[0-9]\d|1500000)$  

我遇到的第一个问题是16-65岁(含)的年龄范围,在这里我不希望小数位.在此处(的正则表达式-90.0到+90.0之间的数字)我以为我可以使用该逻辑并将其置之不理,但不能!

The first one I am having problems for is an age range of 16-65 (inclusive), where I want no decimal places. After a post on here (Regular expression to allow numbers between -90.0 and +90.0) I thought I could use the logic and get it sussed, but can't!

我要表达的是:

(\d|([1-6][6-4]))|65  

有人可以告诉我我对此有何误解!对于以上其他示例的任何帮助,将不胜感激.

Can someone please tell me where I'm misunderstanding this! And any help with the other examples above would be gratefuly received.

推荐答案

很抱歉,但是您的正则表达式都无法正常工作.请记住,正则表达式旨在匹配文本数据.尽管可以使用它们来匹配数字,但实际上并不是首选工具.

Sorry to say this, but none of your regexes are going to work. Remember that regular expressions are designed to match textual data. While it's possible to use them to match numbers, it's not really the tool of choice.

如果必须使用正则表达式,则需要考虑数字范围可能的 textual 表示形式.

If you have to use a regex, you need to think of the possible textual representations of a number range.

对于您的示例1 ,应为:

  1. 一位数字
  2. 或1到3之间的数字,然后是任意数字
  3. 或4,后跟0到5之间的数字.

作为正则表达式:

^(?:\d|[1-3]\d|4[0-5])$

^ $ 锚确保对整个字符串求值;(?:...)分组更改并从锚点屏蔽"它.

The ^ and $ anchors make sure that the entire string is evaluated; the (?:...) groups the alternation and "shields" it from the anchors.

对于您的示例3 :

  1. 1,然后是6-9
  2. 或2-5,后跟任意数字
  3. 或6,然后是0-5

作为正则表达式:

^(?:1[6-9]|[2-5]\d|6[0-5])$

对于您的示例5 :

  1. 1-5位数字
  2. 或1,然后是0-4,后跟任意四个数字
  3. 或150000.

作为正则表达式:

^(?:\d{1,5}|1[0-4]\d{4}|150000)$

以此类推.

添加小数位数不是很困难:

Adding decimal places is not very difficult:

  • \.\ d {2} 仅精确到两位小数位
  • \.\ d {1,3} 保留1至3个小数位
  • (?:\.\ d {1,2})保留0到2个小数位(并且仅当后面至少一位数字时才允许使用点).
  • \.\d{2} works for exactly two decimal places
  • \.\d{1,3} for 1 to 3 decimal places
  • and (?:\.\d{1,2}) for 0 to 2 decimal places (and the dot is only allowed if at least one digit follows).

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

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