75

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. 
2
  • I'd add one more potential issue - parentheses used instead of a sign. It's a fairly common convention in accounting. Commented Dec 9, 2008 at 20:38
  • The MSDN one you cited allows 00000000042. Bleh.
    – Madbreaks
    Commented Feb 9, 2018 at 1:15

15 Answers 15

115

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})?)$
12
  • Do you have a link to the Regex Buddy library? Is it posted online? Commented Dec 9, 2008 at 22:04
  • 2
    Very old now but this regex does not handle the optional commas very well. The number 11111111,111,111111.11 is obviously malformed, but this regex will match it.
    – OGHaza
    Commented Dec 15, 2013 at 21:10
  • 3
    @Keng, I agree it meets OPs needs, was only making note since this is the answer to a question called What is “The Best” U.S. Currency RegEx
    – OGHaza
    Commented Dec 16, 2013 at 17:12
  • 7
    I think we can fix the optional comma issue by replacing (?:,?[0-9]{3})* with something like (?:(,[0-9]{3})*|([0-9]{3})*). Commas everywhere or no commas. Commented Feb 24, 2015 at 16:37
  • 1
    This answer would be improved with example numbers above the regex, rather than (or as well as) word descriptions.
    – Andrew
    Commented Mar 23, 2019 at 23:54
25

I found this regular expression on line at www.RegExLib.com by Kirk Fuller, Gregg Durishan

I've been using it successfully for the past couple of years.

"^\$?\-?([1-9]{1}[0-9]{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))$|^\-?\$?([1-9]{1}\d{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))$|^\(\$?([1-9]{1}\d{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d{0,}(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2}))\)$"
6
  • 4
    While my testing is not authoritative, this one worked for me. Accepted: 123 123.00 $123.00 1234 $1234 $1234.00 $1,234.00 Rejected: #123 1,2,34 Only problem I found is that it accepted 123.4 Commented Sep 25, 2012 at 11:20
  • 1
    Works, guys at work want 123.4 as a valid dollar amount. Commented Jan 20, 2014 at 15:59
  • 1
    this is the way Commented May 13, 2021 at 13:00
  • How does one run this in javascript?
    – Phil
    Commented Feb 25, 2022 at 20:03
  • For my case, 123.4 is fine - if people don't know how to export from Excel properly they might export 123.4 instead of .40, and I found Tabula sometimes misses the last digit on some imports. This is the way.
    – J. Gwinner
    Commented Mar 13, 2022 at 22:36
11

Not thoroughly tested at all (I just wrote it!), but seems to behave correctly:

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

Test set:

0
1
33
555
4,656
4656
99,785
125,944
7,994,169
7994169
0.00
1.0
33.78795
555.12
4,656.489
99,785.01
125,944.100
-7,994,169
-7994169.23 // Borderline...

Wrong:
000
01
3,3
5.
555,
,656
99,78,5
1,25,944
--7,994,169
0.0,0
.10
33.787,95
4.656.489
99.785,01
1-125,944.1
-7,994E169

Note: Your System.Decimal is locale dependent, hard to make in regex, except perhaps when building it. I assumed digits being grouped by three, even if in some cultures (locales) there are different rules.
It is trivial to add whitespace around it.

1
  • @RonRoyston The original question required digits to be present before the decimal symbol... (see the .10 case in the wrong testset). And 0.75 does pass, when I go to regex101.com, paste my expression and add your two cases.
    – PhiLho
    Commented Oct 5, 2018 at 13:46
3

In case you want to account for human error you could make the the regex more forgiving when matching currency. I used Keng's 2nd nice regex and made it a bit more robust to account for typo's.

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

This will match any of these proper or mangled currency figures but not pick up the extra junk on the end after the space:

$46,48382
$4,648,382
$ 4,648,382
$4,648,382.20
$4,648,382.2
$4,6483,82.20
$46,48382 70.25PD
$ 46,48382 70.25PD
3

The answer of Keng is perfect, I just want add that for working with 1 or 2 decimals (for third version) :

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

NET FIDDLE: https://dotnetfiddle.net/1mUpX2

3

regex_expression

/^[-]?[$]\d{1,3}(?:,?\d{3})*\.\d{2}$/ is what I came up with - I see similar answers, but I just used \d instead of [0-9]

2
  • Where does this screenshot come from? Commented May 26, 2021 at 11:25
  • 2
    It's from regexr.com under the regex you can click "Tests" Commented Dec 14, 2022 at 15:41
2

I'm using the following regular expression for currency validation:

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

You can also allow optional leading dollar sign:

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

You can easily add testing for parentheses instead of sign by adding

\( and \)
2

This question is a few years old, so I wanted to give an updated answer.

I have used jQuery InputMask and it works very well for input/format masking (such as phone numbers, etc) but it does NOT really work well for currency from my experience.

For currency, I strongly recommend autoNumeric jQuery plugin. It's well-maintained and they've basically "thought of everything" I could want for currency.

I actually use a combination of both of these plugins for formatting phone numbers, number formats (ISBN, etc), as well as currencies (US currency mostly).

Keep in mind that jquery.inputmask is mostly about controlling a value's format, whereas autoNumeric is about specifically controlling the format of currency.

3
  • Indeed, trying to use a regex only will only lead you to pain and despair. Take a look at the number of AutoNumeric lines of code (as of today) : ~/dev/autoNumeric » cat src/*|wc -l -> 10851. This is just the most complete library today for formatting currencies, and it's thoroughly tested indeed ;) (Disclaimer; I'm one of it's maintainer)
    – Alex
    Commented Jul 20, 2017 at 6:12
  • Can you give an example with using this library to extract a currency value from a string?
    – Ari
    Commented Mar 28, 2019 at 14:10
  • 1
    @Ari: these libraries are more about controlling the format of data when a user enters them into input fields; I don't use them for extracting currency from strings. To extract currency from a string you could use regex to remove anything that isn't 0-9 and a decimal, and then convert that to a float, and then I recommend storing monetary values as cents in the DB. Untested pseudocode: "$123,456.78".gsub(/^[0-9]\./, "").to_f => 123456.78 (note this allows multiple decimal places, but proof of concent).
    – Dan L
    Commented Mar 28, 2019 at 20:05
1

I was looking at this too and have come to the conclusion that it is best to build the regex based on the current culture. We can use the

CurrencyPositivePattern 
CurrencyGroupSeparator
CurrencyDecimalSeparator

properties of NumberFormatInfo to get the required format.

Edit: something like this

NumberFormatInfo nfi = CultureInfo.CurrentCulture.NumberFormat;
      // Assign needed property values to variables.
      string currencySymbol = nfi.CurrencySymbol;
      bool symbolPrecedesIfPositive = nfi.CurrencyPositivePattern % 2 == 0;
      string groupSeparator = nfi.CurrencyGroupSeparator;
      string decimalSeparator = nfi.CurrencyDecimalSeparator;

      // Form regular expression pattern.
      string pattern = Regex.Escape( symbolPrecedesIfPositive ? currencySymbol : "") + 
                       @"\s*[-+]?" + "([0-9]{0,3}(" + groupSeparator + "[0-9]{3})*(" + 
                       Regex.Escape(decimalSeparator) + "[0-9]+)?)" + 
                       (! symbolPrecedesIfPositive ? currencySymbol : ""); 

refer - http://msdn.microsoft.com/en-us/library/hs600312.aspx

2
  • @Robert-levy: added reference msdn.microsoft.com/en-us/library/hs600312.aspx Commented Apr 6, 2012 at 20:09
  • This could probably be improved by saying that it is for c# Commented Aug 4, 2021 at 15:30
1

I've had success with this (taking bits and pieces from some of the regexs above). Only handles up to thousands, but should be not too hard to extend that

case class CurrencyValue(dollars:Int,cents:Int)
def cents = """[\.\,]""".r ~> """\d{0,2}""".r ^^ {
  _.toInt
}
def dollarAmount: Parser[Int] = """[1-9]{1}[0-9]{0,2}""".r ~ opt( """[\.\,]""".r ~> """\d{3}""".r) ^^ {
  case x ~ Some(y) => x.toInt * 1000 + y.toInt
  case x ~ None => x.toInt
}
def usCurrencyParser = """(\$\s*)?""".r ~> dollarAmount ~ opt(cents) <~ opt( """(?i)dollars?""".r) ^^ {
  case d ~ Some(change) => CurrencyValue(d, change)
  case d ~ None => CurrencyValue(d, 0)
}
1

This is what I use:

Without leading + or -

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

With optional leading + or -

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

net fiddle: https://jsfiddle.net/compsult/9of63cwk/12/

1

Using Leandro's answer I added ^(?:[$]|) to the beginning to allow for a preceding dollar sign

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

This matched

136,402.99
25.27
0.33
$584.56
1
00.2
3,254,546.00
$3,254,546.00
00.01
-0.25
+0.85
+100,052.00

Did Not Match

11124.52
234223425.345
234.
.5234
a
a.23
32.a
a.a
z548,452.22
u66.36
0

What about this one? Shorter and elegant

(?:\,|\.?\d)*
0

posting because i didn't see an answer that disallows you from putting more than 3 digits before the a potential first comma. This worked for me:

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

basically replaces(?:,?\d{3})* in other answers with ((,[0-9]{3})*|([0-9]{3})*). you can add back the (?: if you want, but I don't fully understand why that's needed in the first place.

0

valid US money, including MS Excel " $-1,123.00 " and Google Sheets "-$1,123.00" (CSV exported) formats

.NET and Java rexEx

^\s?(\$|[+-]\$|\$[+-]|[+-])?(\d+|\d{1,3}(,\d{3})*)(\.\d{1,2})?\s?$
ELEMENT DESCRIPTION RegEx
[ ] Optional leading space \s?
[$|-$|$-|-] Optional currency with optional negative (or '+') sign (\$|[+-]\$|\$[+-]|[+-])?
0000 CASE 1: no thousand separators (\d+|
0,000 CASE 2: valid US separators, grouped by 3 (and only 3) digits \d{1,3}(,\d{3})*)
[.00] Optional cents with (max) 2 decimals (\.\d{1,2})?
[ ] Optional trailing space \s?

Parse to java BigDecimal

var format = new DecimalFormat("#,###.##", new DecimalFormatSymbols(Locale.US));
format.setParseBigDecimal(true);

String value = " $-12,348.9 ";
value = value.trim().replace("$", "");
return (BigDecimal) format.parse(value);

Test

https://regex101.com/r/fCmNqb/1 RegEx test

Not the answer you're looking for? Browse other questions tagged or ask your own question.