增强千位分隔符的正则表达式? [英] Enhancing regex of thousands separator?

查看:87
本文介绍了增强千位分隔符的正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到了这个漂亮的脚本,可以在js数字中添加数千个分隔符:

I saw this beautiful script to add thousands separator to js numbers:

function thousandSeparator(n, sep)
{
    var sRegExp = new RegExp('(-?[0-9]+)([0-9]{3})'),
        sValue = n + '';
    if(sep === undefined)
    {
        sep = ',';
    }
    while(sRegExp.test(sValue))
    {
        sValue = sValue.replace(sRegExp, '$1' + sep + '$2');
    }
    return sValue;
}

用法:

thousandSeparator(5000000.125, '\,') //"5,000,000.125"

但是我在接受 while循环时遇到了麻烦.

However I'm having a trouble accepting the while loop.

我正在考虑将正则表达式更改为:'(-?[0-9] +)([0-9] {3})*' 星号...

I was thinking to change the regex to : '(-?[0-9]+)([0-9]{3})*' asterisk...

但是现在,我该如何应用replace语句?

but now , how can I apply the replace statement ?

现在我将拥有 $ 1 $ 2 .. $ n

如何增强替换功能?

p.s.该代码摘自此处 http://www.grumelo.com/2009/04/06/thousand-separator-in-javascript/

推荐答案

您的假设

现在我将拥有$ 1和$ 2 .. $ n

now i will have $1 and $2..$n

是错误的.您有两组,因为您有两组括号.

is wrong. You have two groups, because you have two sets of brackets.

    (-?[0-9]+)([0-9]{3})*
1.  ^^^^^^^^^^
2.            ^^^^^^^^^^

然后您重复第二组.如果第二次匹配,它将覆盖第一次匹配的结果,当第三次匹配时,它将覆盖...

And then you repeat the second group. If it matches the second time, it overwrites the result of the first match, when it matches the third time, it overwrites ...

这意味着匹配完成后, $ 2 包含该组中最后一个匹配项的值.

That means when matching is complete, $2 contains the value of the last match of that group.

第一种方法

(\d)(?=(?:[0-9]{3})+\b)

并替换为

$1,

请参见在Regexr上查看

它的缺点是确实在点的右侧也插入了逗号.(我正在努力.)

It has the flaw that it does insert the comma also on the right of the dot. (I am working on it.)

第二种方法

(\d)(?:(?=\d+(?=[^\d.]))(?=(?:[0-9]{3})+\b)|(?=\d+(?=\.))(?=(?:[0-9]{3})+(?=\.)))

并替换为

$1,

请参见在Regexr上查看

所以现在变得更加复杂了.

So now its getting a bit more complicated.

(\d)                   # Match a digit (will be reinserted)
(?:
    (?=\d+(?=[^\d.]))  # Use this alternative if there is no fractional part in the digit
    (?=(?:\d{3})+      # Check that there are always multiples of 3 digits ahead
    \b)                # Till a word boundary
    |                  # OR
    (?=\d+(?=\.))      # There is a fractional part
    (?=(?:\d{3})+      # Check that there are always multiples of 3 digits ahead
    (?=\.))            # Till a dot
)

问题:如果后面没有字符串的末尾,则也会匹配小数部分.

Problem: does also match the fractional part if there is not the end of the string following.

这篇关于增强千位分隔符的正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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