GuidoG
GuidoG

Reputation: 12014

how to get this regex to also accept negative values

I have no knowledge of regular expressions and find the documentations so hard to understand. Currently I use this expression

@"\d+(\R.\d{0,2})?"  

It only allows decimals which is what I want but it does not allows negative numbers.

I found this question about the same subject :
How do I include negative decimal numbers in this regular expression? but I just cannot see what I need to change in my expression to get it working.

I would appreciate some help with this. If there is some documentation on the subject that is clear to read and understand that would also be nice.

Upvotes: 0

Views: 135

Answers (2)

Oscar Vicente Perez
Oscar Vicente Perez

Reputation: 857

Use ^-?\d+(?:\.\d{0,2})?$, but your regex allows numbers like 20. so i suggest to chage it at least for this one ^-?\d+(?:\.\d{1,2})?$.

Also don't forget the ^ and the $. You can use www.regex101.com/, where you can try regex and watch a good documentation.

Upvotes: 2

Iglesk
Iglesk

Reputation: 1541

you can include the - as @"[+-]?\d+(\R.\d{0,2})?"

Check this simple Cheat sheet for C# regular expressions metacharacters, operators, quantifiers etc and For sure https://regex101.com is the best place Online regex tester

Upvotes: 1

Related Questions