Regex for currency number, how can I write it shorter?

^((?=.*[1-9]|0)(?:\d{1,3}))((?=.*\d)(?:\.\d{3})?)*((?=.*\d)(?:\,\d\d){1}?){0,1}$ 

I really think this regex is very long and may be shorter. The problem is that I'm not very good with regular expressions, so I ask you for help.

Online Regular Expression Tester http://regexr.com/3a3mk

My rules:

  • Starting with 1, 2, or 3 positive numbers [1-9] or 0.
  • Adding a number. (followed by 3 numbers [0-9]) as you wish.
  • Ability to add a comma with two digits (as decimal)

Positive results

  • 0
  • 0.55
  • 1
  • 1,60
  • 10
  • 1070
  • 100
  • 100.80
  • 1.10
  • 1,000
  • 1,000,000
  • 10,000
  • 10.000.03
  • 100,000
  • 100,000.08
  • 1,000,000,000
  • 1,000,000,000,10

Negative results

  • 0,0
  • 1,1
  • 1000
  • 1000.000
  • 0,000
  • 0.000.10
  • 1,000,000
  • 1,000,000
  • 1.0.00
  • 1.00.00
  • 1,000,000
  • 01
  • 012.10
  • 012.123,10
  • a
  • a0
  • 0, and
  • 0, aa
  • 1.a00.00
  • 1.000.a1

[EDIT] Added more negative results

+5
source share
3 answers

Edited by:

^(0|[1-9][0-9]{0,2}(\.[0-9]{3})*)(,[0-9]{2})?$

matches:

^ start of line

[1-9] only one nonzero digit

[0-9]{0,2} between 0 and 2 digits

(\.[0-9]{3})* zero or a longer period and 3 digits

(0 | [1-9][0-9]{0,2}(\.[0-9]{3})*) either (i) zero or (ii) up to three digits (the first is not zero ) followed by blocks with zero or more lots of the period, followed by three digits

(,[0-9]{2})? zero or one batch of comma and 2 digits

$ end of line

+2
source

The following should suit your needs:

 ^(?:0|[1-9]\d{0,2})(?:\.\d{3})*(?:,\d{2})?$ 

Regular expression visualization

Visualization of Debuggex

Demo on regex101

+8
source

You are right that your expression is a little long. The shorter version that works with the sample numbers and specifications you provided will be:

 ^(0|\d{1,3})(\.\d{3})*(,\d{2})?$ 

Explanation:

  • (0|\d{1,3}) checks for 0 or 1 to 3 digits
  • (\.\d{3})* checks for a point and 3 numbers, but due to * there cannot be any of them either
  • (,\d{2})? ckecks for a comma and two digits, but again it may appear once or not at all.

Hope this helps you!

+1
source

Source: https://habr.com/ru/post/1209431/


All Articles