Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

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

I actually think this regular expression is very long, and mayby could be shorter. The problem is i'm not very good with regular expressions and therefore I ask you for help.

Online regex tester http://regexr.com/3a3mk

My rules:

  • Starting with 1, 2 or 3 positive numbers [1-9] or 0.
  • Adding as many . (followed by 3 numbers [0-9]) as you want.
  • Possibility to add a comma with 2 numbers (as decimals)

Positive results

  • 0
  • 0,55
  • 1
  • 1,60
  • 10
  • 10,70
  • 100
  • 100,80
  • 1,10
  • 1.000
  • 1.000,20
  • 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
  • 1,000
  • 1000.000
  • 0.000
  • 0.000,10
  • 1.000,1
  • 1.000,100
  • 1.0,00
  • 1.00,00
  • 1.000,0
  • 01
  • 012,10
  • 012.123,10
  • a
  • a0
  • 0,a
  • 0,aa
  • 1.a00.00
  • 1.000.a1

[EDIT] Added more negative results

like image 547
Marcel Avatar asked Dec 18 '14 08:12

Marcel


People also ask

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.

What is $1 in regex replace?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.

How do you write numbers in regex?

Definition and Usage. The [0-9] expression is used to find any character between the brackets. The digits inside the brackets can be any numbers or span of numbers from 0 to 9. Tip: Use the [^0-9] expression to find any character that is NOT a digit.

How do you write special characters in regex?

Special Regex Characters: These characters have special meaning in regex (to be discussed below): . , + , * , ? , ^ , $ , ( , ) , [ , ] , { , } , | , \ . Escape Sequences (\char): To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \.


2 Answers

The following should suit your needs:

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

Regular expression visualization

Visualization by Debuggex

Demo on regex101

like image 145
sp00m Avatar answered Oct 23 '22 10:10

sp00m


Edited:

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

matches:

^ beginning of line

[1-9] just one non-zero digit

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

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

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

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

$ end of line

like image 26
Tony Avatar answered Oct 23 '22 11:10

Tony