RegEx用于检查数字是否小于或大于 [英] RegEx for checking if number is less or greater than

查看:128
本文介绍了RegEx用于检查数字是否小于或大于的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要表达式来检查数字7是否小于30和大于1.这是一个例子。任何人都可以提供表达式和解释?

解决方案

不要使用正则表达式,但如果你想,在这里你去: / $>

$ $ $
$ $ $ $ $ $ $ $ $ $ / code>



Debuggex Demo




解释:

这固定在字符串的开头/结尾(所以我们在数字 175 7 >),然后所有的逻辑发生在非捕获组。匹配数字 [2-9] (大于1) OR 匹配 [1-2] 后跟任何数字 [0-9] (范围从10-29)。请注意,我使用 [0-9] 而不是 \ d ,因为它更适合可读性和 \ d 在技术上将与其他数字字符(阿拉伯语等)相匹配。




注意,如果你想允许前导0( 1 <007 == 7 <30 ),你可以在字符串开始后允许0 + 0 :

  ^ 0 *(?:[2-9] | [1-2] [0-9])$ 


I need expression to check if number 7 is less than 30 and greater than 1. This is an example. Can anybody provide expression and an explanation?

解决方案

Don't use regex, but if you want to, here you go:

^(?:[2-9]|[1-2][0-9])$

Debuggex Demo


Explanation:

This anchors to the beginning/end of the string (so we don't match 7 in the number 175) and then all of the logic happens in the non-capturing group. Either match the numbers [2-9 ] (greater than 1) OR match [1-2] followed by any digit [0-9] (range from 10-29). Notice that I used [0-9] instead of \d because it fits better for readability and \d technically will match other numeric characters (Arabic, etc).


Side note, if you want to allow leading 0's (1 < 007 == 7 < 30), you can allow for 0+ 0's after the start of the string:

^0*(?:[2-9]|[1-2][0-9])$

这篇关于RegEx用于检查数字是否小于或大于的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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