dshtze500055 2019-04-29 07:47
浏览 281
已采纳

在Go正则表达式中分割浮点字符串

I'm, trying to split a certain string type to its constituents using Golang's regex.

What I have is a Sprinf(".2f", n) of any given float (to simplify it to 2 decimal places), and would wish to separate the hundredths digit like:

"1.25" = ["1.2", "5"]
"1.99" = ["1.9", "9"]

In PHP, this is something like:

preg_match('/^ (\-? \d [.] \d) (\d) $/x', sprintf('%1.2f', $input), $matches)

and I can get the parts via $matches[0] and $matches[1].

Tried it with :

re := regexp.MustCompile(`/^ (\-? \d [.] \d) (\d) $/x`)
fmt.Printf("%q
", re.FindAllStringSubmatch("1.50", 2))

to no avail. Thanks in advance.

  • 写回答

1条回答 默认 最新

  • douyazi1129 2019-04-29 07:55
    关注

    Why do you need regexp for this? Simply slice the string:

    func split(s string) []string {
        if len(s) == 0 {
            return nil
        }
        return []string{s[:len(s)-1], s[len(s)-1:]}
    }
    

    Testing it:

    nums := []string{
        fmt.Sprintf("%.2f", 1.25),
        fmt.Sprintf("%.2f", 1.99),
        fmt.Sprintf("%.2f", 1.25),
        fmt.Sprintf("%.2f", 1.2),
        fmt.Sprintf("%.2f", 0.0),
        fmt.Sprintf("%.2f", -1.2),
        "",
    }
    for _, n := range nums {
        fmt.Printf("%q = %q
    ", n, split(n))
    }
    

    Output (try it on the Go Playground):

    "1.25" = ["1.2" "5"]
    "1.99" = ["1.9" "9"]
    "1.25" = ["1.2" "5"]
    "1.20" = ["1.2" "0"]
    "0.00" = ["0.0" "0"]
    "-1.20" = ["-1.2" "0"]
    "" = []
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献