javascript - Extract numbers, dot and comma using regex match - Stack Overflow

admin2025-04-19  0

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

var amount = '$50,000.00Fund Transfer to XXXX9090 Ref #0675'.match(/[^0-9,.]/);

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

var amount = '$50,000.00Fund Transfer to XXXX9090 Ref #0675'.match(/[^0-9,.]/);
Share Improve this question edited Feb 28, 2020 at 10:25 Nirdesh Kumawat asked Feb 28, 2020 at 10:02 Nirdesh KumawatNirdesh Kumawat 4062 gold badges20 silver badges59 bronze badges 2
  • 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 Commented Feb 28, 2020 at 10:05
  • Does this answer your question? Learning Regular Expressions – jonrsharpe Commented Feb 28, 2020 at 10:06
Add a ment  | 

4 Answers 4

Reset to default 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]

^ 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,\.]+/

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 (ma ,):

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}

Match if the string starts with one, two or three digits, followed by any amount of sets that include exactly a ma 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})|)
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745066782a283035.html

最新回复(0)