Reputation: 1721
I need to check this format;
1.234.567,89
Only one comma is permitted for the Entry.
Current code
Regex.Match(((TextChangedEventArgs)e).NewTextValue, @"^[0-9]+(\,[0-9]+)?$");
How can I achieve this?
Upvotes: 1
Views: 442
Reputation: 31656
Use regex to enforce possibilities by using non capturing lookaheads (?=
?!
) which we can enforce all rules before a match.
Rules are
These patterns are commented so use the option IgnorePatternWhitespace
or remove comments and join on one line.
Comma Required
^
(?=[\d\.,]+\Z) # Only allow decimals a period or a comma.
(?=.*,) # Enforce that there is a comma ahead.
(?!.*\.\.) # Fail match if two periods are consecutive.
.+ # All rules satisfied, begin matching
$
Comma and following value optional
^
(?=[\d\.,]+\Z) # Only allow decimals a period or a comma.
(?!.*\.\.) # Fail match if two periods are consecutive.
[\d.]+ # All rules satisfied, begin matching
(,\d+)? # If comma found, allow it but then only have decimals
$ # This ensures there are no more commas and match will fail.
Upvotes: 0
Reputation: 460168
You should not use regex to check if a string can be parsed to a decimal
/double
. Use decimal.TryParse
(or double.TryParse
):
string moneyText = "1.234.567,89";
var myCulture = new CultureInfo("de-DE");
decimal money;
bool validFormat = decimal.TryParse(moneyText, NumberStyles.Currency, myCulture, out money);
if (validFormat)
Console.WriteLine("Valid format, parsed value was " + money.ToString("C"));
Upvotes: 6