[英]Match floating point ONLY with Regex
I have a working regex that matches floating point as well as integer but I need one to only match floating point (number of decimals can be any).我有一个匹配浮点数和整数的工作正则表达式,但我只需要一个匹配浮点数的正则表达式(小数位数可以是任意的)。
This is what I have so far这是我到目前为止
Regex regex = new Regex(@"^-?(?=.*[1-9])\d+(\.\d+)?$", RegexOptions.IgnoreCase);
How do I mod it to only match the floating point?如何将其修改为仅匹配浮点数?
The regex you're looking for is (I've split it into groups for the explanation):您正在寻找的正则表达式是(我已将其分成几组以进行解释):
Regex regex = new Regex(@"^(\+?)([0-9]*)(\.)([0-9]+)$");
Explanation:解释:
Group 1 - an optional plus sign at the beginning.第 1 组 - 开头的可选加号。
Group 2 - optional digits before the dot (why optional? because, for example, .345
is a valid number - and stands for 0.345
).第 2 组 - 点前的可选数字(为什么可选?因为,例如, .345
是一个有效数字 - 代表0.345
)。
Group 3 - the decimal dot.第 3 组 - 小数点。
Group 4 - numbers after the dot.第 4 组 - 点后的数字。 One comment: This regex will accept numbers such as 12345.0
although is not a really decimal.一个评论:这个正则表达式将接受诸如12345.0
数字,尽管它不是一个真正的小数。 I don't see how to solve this just with regex (without code).我不知道如何仅使用正则表达式(没有代码)来解决这个问题。
I think you need this one我想你需要这个
Regex regex = new> Regex(@"^([-+]?)(([0]{1})|([1-9]+([0-9]*)))(\.)([0-9]+)$");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.