doudun3910 2017-12-30 01:25
浏览 35
已采纳

去提供可变消毒吗?

I am a beginner in Golang. I have a problem with variable type assigning from user input.

When the user enters data like "2012BV352" I need to be able to ignore the BV and pass 2012352 to my next function.

There has a package name gopkg.in/validator.v2 in doc

But what it returns is whether or not the variable is safe or not.

I need to cut off the unusual things.

Any idea on how to achieve this?

  • 写回答

1条回答 默认 最新

  • dsv38843 2017-12-30 04:06
    关注

    You could write your own sanitizing methods and if it becomes something you'll be using more often, I'd package it out and add other methods to cover more use cases.

    I provide two different ways to achieve the same result. One is commented out.

    I haven't run any benchmarks so i couldn't tell you for certain which is more performant, but you could write your own tests if you wanted to figure it out. It would also expose another important aspect of Go and in my opinion one of it's more powerful tools... testing.

    package main
    
    import (
        "fmt"
        "log"
        "regexp"
        "strconv"
        "strings"
    )
    // using a regex here which simply targets all digits and ignores everything else.  I make it a global var and use MustCompile because the
    // regex doesn't need to be created every time.
    var extractInts = regexp.MustCompile(`\d+`)
    
    func SanitizeStringToInt(input string) (int, error) {
        m := extractInts.FindAllString(input, -1)
        s := strings.Join(m, "")
        return strconv.Atoi(s)
    }
    
    
    /*
    
    // if you didn't want to use regex you could use a for loop
    func SanitizeStringToInt(input string) (int, error) {
        var s string
        for _, r := range input {
            if !unicode.IsLetter(r) {
                s += string(r)
            }
        }
    
        return strconv.Atoi(s)
    }
    
    */
    
    
    func main() {
        a := "2012BV352"
        n, err := SanitizeStringToInt(a)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(n)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数