正则表达式使用 Google Apps 脚本格式化字符串中的数字

Regex to format number in string using Google Apps script

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

输入字符串:"Price starting from Rs.100000, 10% discount " 或 "Price starting from Rs.100,000, 10% discount" 预计输出:"Price starting from Rs.1,00,000, 10% discount"

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

使用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);
});