浮点的正则表达式? [英] Regex for floating point?
问题描述
我正在尝试编写一个 RegEx 来验证浮点数.以下是我迄今为止所管理的:
I'm trying to write a RegEx to validate a floating point number. Here's what I've managed thus far:
/^[-+]?[1-9]\d{0,2}(\.\d{1,1})?/
该号码在以下情况下有效:
The number is valid if:
- 无论是正面还是负面
- 最多 2 位数字(十位或百位)
- 百分位不能是 0(只能是 1-9)
- 比例最大为 1
- 十进制值可以是 0 或 5 或根本没有
所以这些数字是有效的,例如:
So these numbers would be valid, for ex:
- 1.5
- -1.5
- 17.5
- 15
- -3
- 30.5
这些数字将无效,例如:
These numbers would be invalid, for ex:
- 1.57
- 3041.5
- 17.59
- 915
- -1.56
- 05.0
推荐答案
正如我在评论中所说的 - 您的第一个非零数字将计算在内,然后再添加两个 - 现在允许使用三位数,例如 915
.要解决这个问题的正则表达式方式(与您的测试用例):
As I said in the comments - your first non-zero digit will count, then you add two more - which will now allow three-digit numbers like 915
. To solve this the regexp way (with your testcases):
^[+-]?(?:(?!0)\d{1,2}|0)(?:\.[05])?$
我使用负前瞻(?!0)
来确保第一个数字不是零,然后只需要所需的数字位数.它还允许 0.5
和类似的通过 |0
析取.如果你更喜欢 .5
,那就是:
I use negative lookahead (?!0)
to make sure the first digit is not a zero, then just require the desired number of digits. It also allows 0.5
and similar through the |0
disjunction. If you prefer .5
, it'll be this:
^[+-]?(?!0)\d{,2}(?:\.[05])?$
如果您想禁止 3.0
(您的规则允许)而只允许 3
(正如您在示例中暗示的那样),请替换最后一部分:
If you want to disallow 3.0
(allowed by your rules) and only allow 3
(as you imply in the examples), replace the last part:
^[+-]?(?:(?!0)\d{1,2}|0)(?:\.5)?$
然而,这比@Arkku 漂亮的 Float(number)
可读性差得多;如果您确实需要,请使用正则表达式.
However, this is much less readable than @Arkku's nice Float(number)
; use regexps if you really need them.
这篇关于浮点的正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!