使用正则表达式从字符串量中删除千位分隔符的最佳方法 [英] Best way to remove thousand separators from string amount using a regex

查看:182
本文介绍了使用正则表达式从字符串量中删除千位分隔符的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些变量,这些变量包含数量,并且想要删除(美国)千位分隔符,但还必须解决以下情况:可能存在非美国格式的数量,其中逗号用于小数而不是千位我不想替换逗号.

I have variables that contain amounts and would like to remove the (US) thousand separators but also have to cover the scenario that there may be non-US formatted amounts where the comma is used for the decimals instead of for the thousands where I don't want to replace the comma.

示例:

  • 1,234,567.00必须变为1234567.00
  • 1,234.00必须变为1234.00
    但是
  • 1.234.567,00需要保持不变,因为不是美国格式(即此处的逗号用于小数点)
  • 1.234,00需要保持不变,因为它不是美国格式(即此处的逗号用于小数)

我当时正在考虑使用以下内容,但不确定,因为我对Regex相当陌生:

I was thinking of using the following but wasn't sure about it as I am pretty new to Regex:

myVar.replace(/(\d+),(?=\d{3}(\D|$))/g, "$1");

什么是最好的解决方案?注意:我只需要支付上述示例中的正常金额,没有特殊情况,如字母/数字组合或1,2,3等.

What is best solution here? Note: I just need to cover normal amounts like the above examples, no special cases like letter / number combinations or things like 1,2,3 etc.

推荐答案

这可能适合您的需求:

,(?=[\d,]*\.\d{2}\b)

Debuggex演示

这篇关于使用正则表达式从字符串量中删除千位分隔符的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆