Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to match German number

I am wondering, how would regular expression for testing correct format of number for German culture would look like.

In German, comma is used as decimal mark and dot is used to separate thousands.

Therefore:

  • 1.000 equals to 1000
  • 1,000 equals to 1
  • 1.000,89 equals to 1000.89
  • 1.000.123.456,89 equals to 1000123456.89

The real trick, seems to me, is to make sure, that there could be several dots, optionally followed by comma separator

like image 843
Zbynek Avatar asked Dec 05 '22 23:12

Zbynek


2 Answers

This is the regex I would use:

^-?\d{1,3}(?:\.\d{3})*(?:,\d+)?$

Regular expression visualization

Debuggex Demo

And this is a code example to interpret it as a valid floating point (notice the parseFloat() after the string replacements).

Edit: as mentioned in Severin Klug's answer, the below code assumes that the numbers are known to be in German format. Attempting to "detect" whether a string contains a German format or US format number is not arbitrary and out of scope for this question. '1.234' is valid in both formats but with different actual values, without context it is impossible to know for sure which format was meant.

var numbers = ['1.000', '1,000', '1.000,89', '1.000.123.456,89'];

document.getElementById('out').value=numbers.map(function(str) {
  return parseFloat(str.replace(/\./g, '').replace(',', '.'));
}).join('\n');
<textarea id="out" rows="10" style="width:100%"></textarea>
like image 121
asontu Avatar answered Dec 17 '22 12:12

asontu


I would have posted this as a comment, but I dont have enough reputation. @funkwurm, your post https://stackoverflow.com/a/28361329/7329611 contains javascript

var numbers = ['1.000', '1,000', '1.000,89', '1.000.123.456,89', '1.2'];
numbers.map(function(str) {
  return parseFloat(str.replace(/\./g, '').replace(',', '.'));
}).join('\n');

which should convert german numbers to english/international ones - which it does for every number with exactly three digits after a german thousands dot like the numbers you use in the example array. BUT - and there is the critical Use-Case-Error: it just deletes dots from any other string with not three digits after it aswell. So if you insert a string like '1.2' it returns 12, if you insert '1.23' it returns 123. And this is a very critical behaviour, if anyone just takes the above code snippet and thinks it'll convert any given number correctly into english ones. Because already correct english numbers will be corrupted! So be careful, please.

like image 33
Severin Klug Avatar answered Dec 17 '22 12:12

Severin Klug