regex - 通过正则表达式将逗号插入数字

标签 regex

我有一个正则表达式来在整数中插入逗号:

(?<=\d)(?=(\d{3})+$)
1829383839 ==> 1,829,383,839

这个正则表达式也包含在问题中:Insert commas into number string

但是,我还想扩展正则表达式,以便能够对十进制数字进行逗号化。例如:

1829383839.2937484 ==> 1,829,383,839.2937484

这是怎么做到的?

最佳答案

这里有一个方法:

  • 查找:(?:^|\G)(\d{1,3})(?=(\d{3})+(?:\.\d+)?$)
  • 替换:$1,

说明:

(?:^|\G)            # beginning of line or restart from last match posiiton
(\d{1,3})           # 1 to 3 digits
(?=                 # positive lookahead, make sure we have after:
    (\d{3})+            # 1 or more times 3 digits
    (?:\.\d+)?          # optional decimal places
    $                   # end of line
)                   # end lookahead

Demo & explanation

关于regex - 通过正则表达式将逗号插入数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58703233/

相关文章:

java - 使用android从字母数字字符串中提取数字

.net - RegEx (? ='\\' ).*$ - 尝试从域\用户名获取用户名

php - REGEX - Preg_replace 搜索动态内容

java - 骡子 ESB : Expression Filter with regex() function

javascript - 在 Javascript 中使用正则表达式解析 XHTML 字符串并将其转换为 DOM

python - 替换除数字之间的逗号

java - 用键值对分隔字符串

javascript - 是否有在字符串中创建转义字符的模式?

regex - R grep匹配点

javascript - 如何编写仅允许数字和 "("、 ")"、 "-"的正则表达式