在数字字符串中插入逗号 [英] Insert commas into number string

查看:26
本文介绍了在数字字符串中插入逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我正在尝试对字符串执行反向正则表达式搜索,以将其分成 3 位数字组.据我从 AS3 文档,在 reg ex 引擎中无法向后搜索.

Hey there, I'm trying to perform a backwards regular expression search on a string to divide it into groups of 3 digits. As far as i can see from the AS3 documentation, searching backwards is not possible in the reg ex engine.

这个练习的重点是在一个数字中插入三元组逗号,如下所示:

The point of this exercise is to insert triplet commas into a number like so:

10000000 => 10,000,000

我正在考虑这样做:

string.replace(/(d{3})/g, ",$1")

但这是不正确的,因为搜索不是从后面发生的,替换 $1 只适用于第一场比赛.

But this is not correct due to the search not happening from the back and the replace $1 will only work for the first match.

我感觉最好使用循环来执行此任务.

I'm getting the feeling I would be better off performing this task using a loop.

更新:

由于 AS3 不支持前瞻,我就是这样解决的.

Due to AS3 not supporting lookahead this is how I have solved it.

public static function formatNumber(number:Number):String
{
    var numString:String = number.toString()
    var result:String = ''

    while (numString.length > 3)
    {
        var chunk:String = numString.substr(-3)
        numString = numString.substr(0, numString.length - 3)
        result = ',' + chunk + result
    }

    if (numString.length > 0)
    {
        result = numString + result
    }

    return result
}

推荐答案

如果您的语言支持正向前瞻断言,那么我认为以下正则表达式会起作用:

If your language supports postive lookahead assertions, then I think the following regex will work:

(d)(?=(d{3})+$)

用 Java 演示:

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class CommifyTest {

    @Test
    public void testCommify() {
        String num0 = "1";
        String num1 = "123456";
        String num2 = "1234567";
        String num3 = "12345678";
        String num4 = "123456789";

        String regex = "(\d)(?=(\d{3})+$)";

        assertEquals("1", num0.replaceAll(regex, "$1,"));
        assertEquals("123,456", num1.replaceAll(regex, "$1,"));
        assertEquals("1,234,567", num2.replaceAll(regex, "$1,"));
        assertEquals("12,345,678", num3.replaceAll(regex, "$1,"));
        assertEquals("123,456,789", num4.replaceAll(regex, "$1,"));    
    }    
}

这篇关于在数字字符串中插入逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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