Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
853 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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('
');
<textarea id="out" rows="10" style="width:100%"></textarea>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...