Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Regex for a french decimal

Tags:

c#

.net

regex

I have been spending hours on that problem, looking everywhere... My problem is simple : we want to check ta the user entered a good number. it can be an integer or a decimal with comas not dots, and infinite numbers after coma.

I tried this

 Regex decimalRegex = new Regex(@"\d+(,\d+)?");

I thought it would be ok but this for instance : 2,324e is true if I try IsMatch on it. Moreover it makes no difference between dots and comas so this 2.23 is ok with IsMatch with my regex.

But I want this to be allowed for example with the number 2 :

2
2,2
2,3243241428483248
31324,232332 (infinite numbers before and after)

and to forbid :

2.2
2,2434214e (any letter)

and ideally forbid (I thought the ? would do the trick but it doesn't)...

2,2,2 or
2.2.2

and allow just one coma... I'm in a french culture otherwise

any champion in regex would have a suggestion ? I even downloaded Expresso to do the job but I couldn't..

like image 410
KitAndKat Avatar asked Nov 23 '25 09:11

KitAndKat


2 Answers

You need to anchor the expression:

Regex decimalRegex = new Regex(@"^\d+(,\d+)?$");

Without ^ at the start and $ at the end, the expression is allowed to match any substring of the string you are testing. The anchors together prohibit substrings from matching.

In other words, your original expression would match any string containing at least one digit.

like image 127
cdhowie Avatar answered Nov 24 '25 23:11

cdhowie


Why not use Int32.TryParse() or Double.TryParse() after setting the correct culture? In your question you've said an Int or a Double, but then said an 'infinite numbers after the comma'. These may not be Ints or Doubles depending on their ranges, TryParse will do the range check for you too...

like image 44
Ian Avatar answered Nov 24 '25 23:11

Ian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!