Search code examples
c#regex

RegEx pattern for sums with optional thousands separator and different decimal points


Sums in invoice are always two decimals after comma. Decimal point may be comma or point. Number may contain single space as thousands separator. Optionally they numbers may start with - sign.

Example:

Subtotal,    1 000.00 EUR
VAT    1000,00
Total, sum:    _343 444.45 EUR

Results should be

1 000.00
1000,00
343 444.45

Which is C# .NET RexExp pattern for this. There are lot of similar questions but havent found excatly same. Using .NET 7 ASP.NET MVC.

Answer in Regex valid numbers with thousand separator assumes that every number is in sepearate line.


Solution

  • -?[0-9]{1,3}(?: ?[0-9]{3})*[.,][0-9]{2}

    Explanation:

    • -? - optional - sign,
    • [0-9]{1,3} - one to three digits. Block of digits before first thousands separator,
    • (?: ?[0-9]{3})* - optional space and block of three digit repeated any number of times,
    • [.,] - dot or comma: decimal separator,
    • [0-9]{2} - two digits: decimal part.

    Demo here.