去提供可变消毒吗?

Hasibul Hasn:

我是Golang的初学者。我从用户输入分配变量类型时遇到问题。

当用户输入数据时,"2012BV352"我需要能够忽略BV和传递2012352给我的下一个功能。

gopkg.in/validator.v2doc中有一个软件包名称

但是它返回的是变量是否安全。

我需要切断不寻常的事情。

关于如何实现这一点的任何想法?

reticentroot:

您可以编写自己的清理方法,如果它变得更常用,我将其打包并添加其他方法来涵盖更多用例。

我提供两种不同的方法来达到相同的结果。一个被注释掉了。

我没有运行任何基准测试,因此无法确定哪个性能更高,但是如果您想弄清楚的话,可以编写自己的测试。它还将暴露Go的另一个重要方面,我认为它是功能更强大的工具之一-测试。

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)
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章