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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?