doumeng9188 2017-05-05 17:15
浏览 600

是否可以在Golang中的一次操作中提取字符串的一部分并替换这些部分?

Say I want to extract all numbers from a string (Most likely using regex matching) and I also want to replace those number matches with a generic placeholder like "#".

This is easily done in two parts using FindAll, then ReplaceAll. However I have serious doubts about the performance costs of doing such operations.

So take a string

"sdasd 3.2% sadas 6 ... +8.9"

replace it with

"sdasd #% sadas # ... +#"

and get a slice

[3.2,6.0,8.9]

In the most performant way possible.

Edit : I implemented the regexp.FindAllString + regexp.ReplaceAllString and the performance hit to my app was very minimal. I will hopefully try Elliot Chance's approach and compare the two when I have time.

  • 写回答

2条回答 默认 最新

  • doumi2106 2017-05-05 17:21
    关注

    If you need raw performance than regexp is rarely the way to achieve it, even if it is convenient. Iterating token by token should be pretty fast. Some code:

    input := "sdasd 3.2 sadas 6"
    output := []string{}
    numbers := []float64{}
    
    for _, tok := range strings.Split(input, " ") {
        if f, err := strconv.ParseFloat(tok, 64); err == nil {
            numbers = append(numbers, f)
            tok = "#"
        }
        output = append(output, tok)
    }
    finalString := strings.Join(output, " ")
    fmt.Println(finalString, numbers)
    

    playground link

    I'm sure there's a few more optimizations in there that could be made, but this is the general approach I'd take.

    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?