【问题标题】:Regex to format number in string using Google Apps script正则表达式使用 Google Apps 脚本格式化字符串中的数字
【发布时间】:2020-03-16 14:02:10
【问题描述】:

我正在尝试将数字格式化为以下格式的字符串:#,##,### 这是我的谷歌脚本代码,但它用#,##,###替换了数字 字符串可以在数字前后有任意数量的字符。 最好和最有效的方法是什么?

输入字符串:“价格从 Rs.100,000 开始,10% 折扣”或“价格从 Rs.100,000 开始,10% 折扣” 预期结果:“价格从 1,00,000 卢比起,10% 折扣”

treated_value3 = treated_value2.replace(/(\d+)/, Utilities.formatString("#,##,##0","$1"));

【问题讨论】:

  • @Wiktor Stribiżew,你能不能请一下?
  • 我无法遵循您上面提到的正则表达式
  • 不,它没有。格式化的字符串返回#,##,##0

标签: regex google-apps-script number-formatting


【解决方案1】:

使用Intl

const str = "Price starting from Rs.100000",
str2 =  "Price starting from Rs.100,000",
str3 = "Pricing starts at Rs.50000000 and get 20% discount, if you order now!";
[str, str2, str3].forEach(str=>{
    const [,prefix, num, suffix] = str.match(/(.*?Rs\.)([\d,]+)(.*)$/);
    const fNum = new Intl.NumberFormat('en-IN').format(num.replace(/,/g,''));
    console.info(`${prefix}${fNum} ${suffix}`);
})

或者,用 string.replace 使用积极的外观:

const str = 'Price starting from Rs.100000',
  str2 = 'Price starting from Rs.100,000',
  str3 =
    'Pricing starts at Rs.50000000 and get 20% discount, if you order now!';
[str, str2, str3].forEach(str => {
  const formatted = str.replace(/(?<=Rs\.)[\d,]+/, num => {
    return new Intl.NumberFormat('en-IN').format(num.replace(/,/g, ''));
  });
  console.info(formatted);
});

【讨论】:

  • 谢谢@TheMaster,数字后面也可能有字符串。例如。 “价格从 100000 卢比起,等等等等”。那么如何使用正则表达式来提取数字并应用格式?我试过了,但输出不正确:
  • @Priyanka 编辑您的问题以显示此类其他变体
猜你喜欢
  • 2017-07-16
  • 2015-07-30
  • 2017-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-20
相关资源
最近更新 更多