Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is "The Best" U.S. Currency RegEx?

Tags:

regex

currency

A quick search for currency regex brings up a lot of results.

The problem I have in choosing one is that regex is difficult to verify without testing all the edge cases. Does anyone have a regex for U.S. currency that has been thoroughly tested?

My only requirement is that the matched string is U.S. currency and parses to System.Decimal:

 [ws][sign][digits,]digits[.fractional-digits][ws]   Elements in square brackets ([ and ]) are optional.  The following table describes each element.   ELEMENT             DESCRIPTION ws                  Optional white space. sign                An optional sign. digits              A sequence of digits ranging from 0 to 9. ,                   A culture-specific thousands separator symbol. .                   A culture-specific decimal point symbol. fractional-digits   A sequence of digits ranging from 0 to 9.  
like image 549
Robert Claypool Avatar asked Dec 09 '08 20:12

Robert Claypool


People also ask

Why is regex expensive?

Poorly written regex patterns are not only costly, they are dangerous. This one has too many consequent subpatterns that can match empty strings. Thus, backtracking falls into them and fails, and re-tries, and fails... That makes your pattern costly.

What is space in regex?

The most common regex character to find whitespaces are \s and \s+ . The difference between these regex characters is that \s represents a single whitespace character while \s+ represents multiple whitespaces in a string.


1 Answers

here's some stuff from the makers of Regex Buddy. These came from the library so i'm confident they have been thoroughly tested.

Number: Currency amount (cents mandatory) Optional thousands separators; mandatory two-digit fraction

Match; JGsoft: ^[+-]?[0-9]{1,3}(?:,?[0-9]{3})*\.[0-9]{2}$ 

Number: Currency amount (cents optional) Optional thousands separators; optional two-digit fraction

Match; JGsoft: ^[+-]?[0-9]{1,3}(?:,?[0-9]{3})*(?:\.[0-9]{2})?$ 

Number: Currency amount US & EU (cents optional) Can use US-style 123,456.78 notation and European-style 123.456,78 notation. Optional thousands separators; optional two-digit fraction

Match; JGsoft: ^[+-]?[0-9]{1,3}(?:[0-9]*(?:[.,][0-9]{2})?|(?:,[0-9]{3})*(?:\.[0-9]{2})?|(?:\.[0-9]{3})*(?:,[0-9]{2})?)$ 
like image 70
Keng Avatar answered Oct 13 '22 06:10

Keng