正则表达式匹配浮点数,但不是整数 [英] Regular expressions match floating point number but not integer

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

问题描述

我有个问题来定义一个匹配浮点数的正则表达式,但是不能识别整数。

我有下面的正则表达式,它和浮点数匹配。 / p>

 (\ + |  - )?([0-9] + \。?[0-9] * | \\ \\ [0-9] +)([EE](\ + |  - )?[0-9] +)? 

如何修改上面的表达式使其不匹配整数? b
$ b

下面是一个应该匹配的例子:

  3.3 
。 3
5E6
.2e-14
7E + 3
4.
5.E2
1e2
如果你的正则表达式支持lookaheads,那么在数字结尾之前需要一个浮点数字符:

 ((\ + |  - )?(?= \ d * [。eE])([0-9 [0-9] +)([eE](\ + |  - )?[0-9] +)?

其他阅读。



这里也是一个稍微优化的版本:

 <$ c ???$ C> [+  - ](?= \d * [EE])(??= \ \d)\d * \ \d *(:[EE] [ +  - ]?\d +)?

我们从一个可选的 + - ,然后我们需要一个之后的任意字符 e E 数字量。那么我们还需要至少一个数字,在字符串之前或之后。我们只是匹配数字,一个可选的和更多的数字。然后(完全可选)一个 e 或一个 E 和可选的 + - 然后输入一个或多个数字。


I have a problem to define a regexp that matches floating point numbers but do NOT identify integers.

I have the following regular expression, which matches floating numbers.

(\+|-)?([0-9]+\.?[0-9]*|\.[0-9]+)([eE](\+|-)?[0-9]+)?

How can I modify the expression above so that it doesn't match integers?

Here is a example of what should be matched:

3.3
.3
5E6
.2e-14
7E+3
4.
5.E2
1e2

解决方案

If your regex flavor supports lookaheads, require one of the floating-point characters before the end of the number:

((\+|-)?(?=\d*[.eE])([0-9]+\.?[0-9]*|\.[0-9]+)([eE](\+|-)?[0-9]+)?

Additional reading.

Here is also a slightly optimized version:

[+-]?(?=\d*[.eE])(?=\.?\d)\d*\.?\d*(?:[eE][+-]?\d+)?

We start with an optional + or -. Then we require one of the characters ., e or E after an arbitrary amount of digits. Then we also require at least one digit, either before or after the string. The we just match digits, an optional . and more digits. Then (completely optional) an e or an E and optional + or - and then one or more digits.

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

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