doucan1979 2013-09-28 08:45
浏览 277
已采纳

用golang解析Perl正则表达式

http://play.golang.org/p/GM0SWo0qGs

This is my code and playground.

func insert_comma(input_num int) string {
    temp_str := strconv.Itoa(input_num)
    var validID = regexp.MustCompile(`\B(?=(\d{3})+$)`)
    return validID.ReplaceAllString(temp_str, ",")
}

 func main() {
    fmt.Println(insert_comma(1000000000))
 }

Basically, my desired input is 1,000,000,000. And the regular expression works in Javascript but I do not know how to make this Perl regex work in Go. I would greatly appreciate it. Thanks,

  • 写回答

1条回答 默认 最新

  • dougong2005 2013-09-28 11:00
    关注

    Since lookahead assertion seems to be not supported, I'm providing you a different algorithm with no regexp:

    Perl code:

    sub insert_comma {
        my $x=shift;
        my $l=length($x);
        for (my $i=$l%3==0?3:$l%3;$i<$l;$i+=3) {
            substr($x,$i++,0)=',';
        }
        return $x;
    }
    print insert_comma(1000000000);
    

    Go code: Disclaimer: I have zero experience with Go, so bear with me if I have errors and feel free to edit my post!

    func insert_comma(input_num int) string {
        temp_str := strconv.Itoa(input_num)
        var result []string
        i := len(temp_str)%3;
        if i == 0 { i = 3 }
        for index,element := range strings.Split(temp_str, "") {
            if i == index {
                result = append(result, ",");
                i += 3;
            }
            result = append(result, element)
        }
        return strings.Join(result, "")
    }
    
    func main() {
        fmt.Println(insert_comma(1000000000))
    }
    

    http://play.golang.org/p/7pvo7-3G-s

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺