Pod Mays
Pod Mays

Reputation: 2583

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

Upvotes: 0

Views: 1568

Answers (2)

stema
stema

Reputation: 92976

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

Upvotes: 1

Williham Totland
Williham Totland

Reputation: 29009

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

Upvotes: 2

Related Questions