开发者

C# Regex for a french decimal

开发者 https://www.devze.com 2023-01-29 23:10 出处:网络
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.

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..


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.


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...


You're pretty much on the right track; the regex you need is @"^(\d+(,\d*)?|,\d+)$" The ^ and $ force the regex to match at the beginning and end of the string, so nothing extra is allowed. Without these, your regex would match 1,2 in 1,2e, and think that was OK—this is also why 2,2,2 was working, since it matched the first 2,2 and ignored the rest. And this is why 2.2.2 matched—the regex matched the 2, and ignored the rest. Basically, anchors are very helpful :-) The other thing I changed was adding a ,\d+ clause, which allows you to match numbers of the form ,123. If you don't want that, take it out (@"^\d+(,\d*)?$"). Similarly, if you don't want to match 123,, then change the * to a + (@"^\d+(,\d+)?$").

If you're open to other solutions, you might take Ian's advice and use an existing function; I'd also suggest replacing the , with [.,] so that people can enter either 1,2 or 1.2, since that doesn't really harm anything but makes life easier for some. (Unless you're really worried about thousands separators, or have some deep reason not to want the second.)

0

精彩评论

暂无评论...
验证码 换一张
取 消