0

I want to find and match currency in a given text. Formats that are accepted are:

  • $10
  • $10.25
  • $999,000
  • $2 billion
  • $625 million

This is my regex so far:

var money_vals =  $('body').text().match(/\$\d+\.?\d+(\,\d+)?(thousand|million|billion|trillion)?/g);

However, it doesn't match $2 billion or the $625 million or any value followed by million/billion/trillion. Also, after adding $5 to one of the paragraphs in my text, I realized it doesn't get matched.

Could anyone please help?

Jamiec
  • 118,012
  • 12
  • 125
  • 175
  • Try the following: \$\d+((,|\.)\d+)?(\s(thousand|million|billion|trillion))? – Camo Oct 29 '15 at 10:43
  • 1
    Possible duplicate of [What is "The Best" U.S. Currency RegEx?](http://stackoverflow.com/questions/354044/what-is-the-best-u-s-currency-regex) – viral Oct 29 '15 at 10:45
  • Most currency symbols are usually written as postfix (dollar is not the only currency in the world). – Jan Turoň Oct 29 '15 at 10:52
  • This worked for me: var money_vals = $('body').text().match(/\$\d+(,\d{3})*(\.\d+)?(thousand| million| billion| trillion|$)?/g); – Zacharia Mwangi Nov 03 '15 at 08:20

3 Answers3

2

A generic form, group 1 matches the number second group the following boundary word

\$[\s]?([\d\.\,]+)[\s]*([\w]*)

http://regexr.com/3c3av

An exact match form :

\$[\s]?([\d\.\,]+)[\s]*(thousand|million|billion|trillion)?

http://regexr.com/3c3as

Tiberiu C.
  • 2,943
  • 26
  • 37
0

You should use the following regex:

/\$\d+[\,\.\d\s]*(?:thousand|million|billion|trillion|$)/ig
Jamiec
  • 118,012
  • 12
  • 125
  • 175
Mayur Koshti
  • 1,582
  • 13
  • 20
0

Try This

var re = /\$[0-9]+[?:, 0-9]*(?:billion|million+)?/;
var sourcestring = "source string to match with pattern";
var results = [];
var i = 0;
for (var matches = re.exec(sourcestring); matches != null; matches = re.exec(sourcestring)) {
 results[i] = matches;
for (var j=0; j<matches.length; j++) {
  alert("results["+i+"]["+j+"] = " + results[i][j]);
}
i++;

}

This will solve your problem.

Yash
  • 1,427
  • 1
  • 11
  • 26