正则表达式匹配浮点数 [英] Regex Matching numbers with floating point
问题描述
我有这个模式:
[0-9]*\.?[0-9]
它匹配数字,但也匹配 3.5.4 为:
It matches numbers but it also matches 3.5.4 as:
- 3.5
- .4
如何解决(此输入不应该匹配)?
更新:
这也应该适用于输入:1 3.5.4 10
How to fix that(this input shouldn't be matched)?
UPDATE:
this also should work on input:
1 3.5.4 10
1.2.不允许
.3 允许
1.2. is not allowed
.3 is allowed
任何不是数字的字符都是不允许的,例如:a1 2.4f 3. 45, 67!
any char that is not poart of numer is not allowed, like: a1 2.4f 3. 45, 67!
推荐答案
根据海报评论更新答案:
Updated answer after comment from poster:
使用lookahead/lookbehind来确保前后的字符都是空格:
Use lookahead / lookbehind to make sure that the characters before and after are spaces:
这是一个与您的版本非常匹配,但不会部分匹配的版本:
Here's a version that closely matches yours, but that won't make partial matches:
(?:^|(?<=\s))[0-9]*\.?[0-9](?=\s|$)
对于这两个例子,当在字符串 1 2.3.4 5.6
上运行时,它只匹配 1
和 5.6
.
For both these examples, when run on the string 1 2.3.4 5.6
it matches only 1
and 5.6
.
这篇关于正则表达式匹配浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!