gpt4 book ai didi

validation - go 是否提供变量清理?

转载 作者:IT王子 更新时间:2023-10-29 02:02:26 26 4
gpt4 key购买 nike

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

当用户输入像 "2012BV352" 这样的数据时,我需要能够忽略 BV 并将 2012352 传递给我的下一个函数。

doc中有包名gopkg.in/validator.v2

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

我需要切断不寻常的东西。

关于如何实现这一点有什么想法吗?

最佳答案

您可以编写自己的清理方法,如果它成为您会更频繁使用的东西,我会将其打包并添加其他方法以涵盖更多用例。

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

我没有运行任何基准测试,所以我不能肯定地告诉您哪个性能更好,但如果您想弄清楚,您可以编写自己的测试。它还将揭示 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)
}

关于validation - go 是否提供变量清理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48030118/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com