正则表达式匹配浮点数 [英] Regex Matching numbers with floating point

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

问题描述

我有这个模式:

[0-9]*\.?[0-9]

它匹配数字,但也匹配 3.5.4 为:

It matches numbers but it also matches 3.5.4 as:

  1. 3.5
  2. .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 上运行时,它只匹配 15.6.

For both these examples, when run on the string 1 2.3.4 5.6 it matches only 1 and 5.6.

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

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