包含小数点的数字的正则表达式

标签 regex

我仍在尝试学习正则表达式,所以我似乎无法弄清楚这个问题。我希望能够匹配任何类型的数字,包括诸如

0.2
.1243
1.
-0.34
+033.98274E-10
-.1e+004

我创建了以下与所有这些匹配的正则表达式:[+-]?[0-9+\.]+([E][+-]?[0-9]+)?,但是这也匹配单个小数点,例如如果我有像 param.attribute 这样的东西,它会在该小数点上拾取。我该如何解决这个问题?我认为在 [0-9+\.] 部分中,+ 要求字符串至少包含一个数值。

最佳答案

您可以使用交替来确保 1..1 匹配。如果您不想最终匹配单个句点,请避免将所有子模式设为可选:

[-+]?(?:[0-9]+\.?[0-9]*|[0-9]*\.?[0-9]+)(?:[eE][-+]?[0-9]+)?
     ^--- Alernative 1 | Alternative 2-^

参见regex demo

更多 "fun" facts about alternation in regular expressions :

You can use alternation to match a single regular expression out of several possible regular expressions.

If you want to search for the literal text cat or dog, separate both options with a vertical bar or pipe symbol: cat|dog. If you want more options, simply expand the list: cat|dog|mouse|fish.

The alternation operator has the lowest precedence of all regex operators. That is, it tells the regex engine to match either everything to the left of the vertical bar, or everything to the right of the vertical bar. If you want to limit the reach of the alternation, you need to use parentheses for grouping.

这是我的 5 美分:为了使正则表达式匹配尽可能干净,除非您需要在找到匹配项后访问任何替代方案,请使用非捕获组(即 (?: ... )) 与交替。

关于包含小数点的数字的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32845317/

相关文章:

php - Apache mod-rewrite 不接受查询字符串中的双引号

javascript - 在需要搜索和替换的代码中转义括号(Sublime Text2)

javascript - Nodejs 的正则表达式全局匹配不起作用

java - 从java中的单词中删除复数后缀

java - 为什么我的正则表达式不匹配?

regex - 匹配任意长度的字字符和/或点字符串

javascript - 在 JavaScript 中计算关键字的最佳方法是什么?

java - 线程 "main"java.util.regex.PatternSyntaxException : Unmatched closing 中出现异常

c# - 删除两个字符之间的字符

javascript - 正则表达式查找字符串中的图像链接