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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法