简体   繁体   中英

TCL regexp for float fails at single digit

I have developed the following regexp to capture float numbers.

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

It works fine for such things as 4.08955e-11 or 3.57 . Now by stupid chance my parser came across 0 and failed. I guess I need to make all following the decimal point optional. But how do I do that?

Contrary to what one might think, matching every possible form of floating point number (including NaN etc) with a manageable regular expression that still discards eg impossibly large numbers or pseudo-octals is non-trivial.

There are some ideas about reducing the risk of false positives by using word boundaries, but note that those match boundaries between word characters (usually alphanumerics and underscore).

The scan command allows simple and reliable validation and extraction of floating point numbers:

scan $number %f

也许使用替代方法:

{[-+]?(?:\y[0-9]+(?:\.[0-9]*)?|\.[0-9]+\y)(?:[eE][-+]?[0-9]+\y)?}

If you make all following the decimal point optional (which itself is optional) you could match values like 2.

Note that your regex does not match a single digit because you match 2 times one or more digits [0-9]+

If you only want to match float numbers or zero you could use an alternation and for example use word boundaries \\b :

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

Explanation

  • [-+]? Match optional + or -
  • \\b Word boundary
  • (?: Non capturing group
    • [0-9]+\\.[0-9]+ match one or more digits dot and one or more digits
    • (?:[eE][-+]?[0-9]+)? Optional exponent part
    • | Or
    • 0 Match literally
  • ) Close non capturing group
  • \\b Word boundary

To match a float value that does not start with a dot and could be one or more digits without a dot you cold use use:

^[-+]?[0-9]+(?:\\.[0-9]+)?(?:[eE][-+]?[0-9]+)?$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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