1

I am trying to extract amount $50,000.00 from string which has number, comma and dot. My code is below:

var amount = '$50,000.00Fund Transfer to XXXX9090 Ref #0675'.match(/[^0-9,.]/);
Nirdesh Kumawat
  • 386
  • 2
  • 16
  • 56
  • 2
    The `^` at the start of a character class means "not", which isn't the behaviour you're describing. Also you only match a single character. – jonrsharpe Feb 28 '20 at 10:05
  • Does this answer your question? [Learning Regular Expressions](https://stackoverflow.com/questions/4736/learning-regular-expressions) – jonrsharpe Feb 28 '20 at 10:06

4 Answers4

3

You can use [\d,]+\.\d+ in case dot is required in the number, like: [\d,]+\.\d+.

In case dot is optional - you may use [\d,]+(\.\d+)?,
but in this case you may capture undesired values like: 9090 and 0675.

As result your code must looks like this:

var amount = '50,000.00Fund Transfer to XXXX9090 Ref #0675'.match(/[\d,]+\.\d+/)[0]

In case this number must be the most left number - like this:

var amount = '50,000.00Fund Transfer to XXXX9090 Ref #0675'.match(/^[\d,]+\.\d+/)[0]
cn007b
  • 16,596
  • 7
  • 59
  • 74
1

^ at a start of a charactor class means not. And also you are missing +. Meaning of your expression is not a digit or , or . and only once

Answer is /^[\d,\.]+/ or /^[0-9,\.]+/

Dum
  • 1,431
  • 2
  • 9
  • 23
0

Try this one - \d{1,3}(,\d{3})*\.\d{2}. It should match only those numbers which are properly formatted with decimal separator (dot .) and thousands separator (comma ,):

const amount = '50,000.00Fund Transfer to XXXX9090 Ref #0675'.match(/\d{1,3}(,\d{3})*\.\d{2}/)[0];

console.log(amount)

You can also match numbers with a dollar sign at the beginning, but you need to escape that character in your regexp, since it has a special meaning (end of string):

\$\d{1,3}(,\d{3})*\.\d{2}

Alexander
  • 77
  • 1
  • 1
  • 6
0

Match if the string starts with one, two or three digits, followed by any amount of sets that include exactly a comma and three digits.

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

Additionally, you could add the following term to optionally allow for exactly two decimals:

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

In your case, the amount has a leading dollar sign, so we would have to alter our regex as follows:

^\$[0-9]{1,3}((\,[0-9]{3})|)+((\.[0-9]{2})|)
ATH
  • 666
  • 6
  • 13