我仍在尝试学习正则表达式,所以我似乎无法弄清楚这个问题。我希望能够匹配任何类型的数字,包括诸如
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-^
更多 "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 textcat
ordog
, 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/