简体   繁体   English

正则表达式检查小数点是否在两个数字之间,而不管小数点后的位数

[英]Regular Expression to check if decimal is between two numbers irrespective of number of digits after decimal point

Can you help me with writing a Regular Expression ( I will use this in Pattern.compile in Java)?你能帮我写一个正则表达式吗(我将在 Java 的 Pattern.compile 中使用它)?

My requirement is我的要求是

Given a decimal, should check if the given decimal is between two numbers,

Example: Given Number 1 : 0, Number 2: 50
a) 0 - true
b) 51 - false
c) 50 - true
d) 10.25 - true
e) 10.2345 - true

I should verify irrespective of number of digits after decimal point.无论小数点后的位数如何,我都应该进行验证。

It will be tricky to implement the generic solution, so I'll leave here the solution for your example and let you think of a generic solution for it.实现通用解决方案会很棘手,所以我将在这里为您的示例留下解决方案,让您为它考虑一个通用解决方案。

Here's your regex: (([0-4]{1}[0-9]{1})|((50){1}))(\\.[0-9]+)*这是您的正则表达式: (([0-4]{1}[0-9]{1})|((50){1}))(\\.[0-9]+)*

To turn it generic you just need to change the first part implementation to the numbers you want to use, you can do it using a loop to concat those groups (this is the first part: ([0-4]{1}[0-9]{1})|((50){1}) ).要使其通用,您只需将第一部分实现更改为您想要使用的数字,您可以使用循环来连接这些组(这是第一部分: ([0-4]{1}[0-9]{1})|((50){1}) )。

So I'm not 100% sure I am understanding the question properly, so I can't be 100% sure it will work for all cases, but here is what I have.所以我不能 100% 确定我正确理解了这个问题,所以我不能 100% 确定它适用于所有情况,但这是我所拥有的。

([0-9]{2}\.[0-9]{2})|([0-9]*0\b)

a) 0 - true a) 0 - 真

b) 51 - false b) 51 - 错误

c) 50 - true c) 50 - 真

d) 10.25 - true d) 10.25 - 正确

e) 10.2345 - true e) 10.2345 - 真

If "."如果 ”。” is between 2 Numbers or ends with 0.介于 2 个数字之间或以 0 结尾。

Here is the example: https://regex101.com/r/295QWt/1这是示例: https : //regex101.com/r/295QWt/1

So my other answer is if a number is between 2 different numbers.所以我的另一个答案是一个数字是否介于 2 个不同的数字之间。 Actually in this case I don't think regex is that useful.实际上在这种情况下,我认为正则表达式没有那么有用。 Depending on the language using regex might even be slower.根据使用正则表达式的语言甚至可能更慢。

if(value > min && value < max){return true;}

Use this regex:使用这个正则表达式:

^(?:[0-4]?\d(?:\.\d+)?|50(?:\.0+)?)$

Demo & explanation演示和说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM