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

在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.

图片转代码服务由CSDN问答提供 功能建议

我正在尝试使用Golang的正则表达式将某种字符串类型拆分为其组成部分。

我所拥有的是任何给定浮点数的 Sprinf(“。2f”,n)(将其简化为2个小数位),并且希望将百分位数分开,例如:

 “ 1.25” = [“ 1.2”,“ 5”] 
“ 1.99” = [“ 1.9”,“ 9”] 
   
 
 

在PHP中,类似于:

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

,我可以通过$ matches [0 ]和$ matches [1]。

尝试过:

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

无济于事。 预先感谢。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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"]
    "" = []
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题