简体   繁体   中英

C# RegEx for decimal number or zero (0)

This gets all numbers but not floating numbers

Regex(@"^\d+$")

I need it to get these values as well:

1234.12345545
0
12313
12313.13
-12131
-1313.13211312

For matching all of the above; the most appropriate regex is probably

@"^[+-]?\d+(\.\d+)?$"

This matches all of the above; but not numbers on the format .3456 .

It also matches numbers on the format +123 and -1234.5678

Try this here

^(?:[-+]?[1-9]\d*|0)?(?:\.\d+)?$

This will additionally match the empty string.

See it online here on Regexr

If matching the empty string is not wanted, then you can add a length check to your regex like

^(?=.+)(?:[-+]?[1-9]\d*|0)?(?:\.\d+)?$

The positive lookahead (?=.+) ensures that there is at least 1 character

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