Regular expression to match German number

前端 未结 5 1262
孤街浪徒
孤街浪徒 2020-12-03 19:26

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 do

5条回答
  •  半阙折子戏
    2020-12-03 20:15

    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');

提交回复
热议问题