-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
  • 332
  • 2
  • 15
  • 52
  • 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

3 Answers3

2

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
  • 15,878
  • 6
  • 57
  • 69
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,321
  • 2
  • 7
  • 22
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
  • 45
  • 1
  • 1
  • 6