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

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

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})|)

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745066781a4609302.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信