简体   繁体   English

仅与正则表达式匹配浮点数

[英]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]+)$");
  • Group 1: Optional "-" sing on the begin.第 1 组:可选的“-”在开始时演唱。
  • Group 2 - 5: The number begin whit 0 OR begin whit another num (1-9) one or more.第 2 - 5 组:数字从 0 开始或从另一个 num (1-9) 一个或多个开始。 In this Case is not posible to match (EX: 001.55 - It's not a float number).在这种情况下不可能匹配(例如:001.55 - 它不是浮点数)。
  • Group 6 - Include "."第 6 组 - 包括“.”
  • Group 7 - Include one or more (0-9)第 7 组 - 包括一个或多个 (0-9)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM