Golang 检查字符串是否为字母数字

Golang 检查字符串是否为字母数字

在本文中,我们将看到如何在Golang中验证字母数字字符串。我们将简单地从用户输入一个字符串并检查该字符串是否为字母数字。我们将使用Go中的regexp模块验证字符串的字母数字模式。

字符串输入

为了从用户获取输入,我们将使用Golang中fmt模块中的Scan函数。我们将把输入存储在一个字符串变量中。

// Golang程序从用户获取输入字符串
package main
import (
    "fmt"
)
func main() {
    var word string
    fmt.Print("输入一个字符串: ")
    fmt.Scan(&word)
} 
Go

在上面的程序中,我们初始化了一个字符串变量。在声明后,我们有一个用于用户输入的简单文本消息。最后,我们使用Scan函数并将输入存储在变量中。

检查字母数字正则表达式

在我们获得用户输入后,我们现在可以开始验证字符串是否为字母数字字符串。要做到这一点,我们将首先导入regexp模块。导入模块后,我们将访问MustCompile和MatchString函数。

// Golang程序检查字母数字正则表达式
package main
import (
    "fmt"
    "regexp"
)
func main() {
    var word string
    fmt.Print("输入一个字符串: ")
    fmt.Scan(&word)
    is_alphanumeric := regexp.MustCompile(`^[a-zA-Z0-9]*$`).MatchString(word)
} 
Go

使用MustCompile函数,我们可以检查正则表达式是否满足。我们解析了字符串^[a-zA-Z0-9_]*,它将从开头到结尾(,它将从开头(^)到结尾()检查任何字符的出现:从0到9,A到Z和a到z。我们将该函数与MatchString组合使用,它将比较正则表达式和传递的字符串。如果匹配了正则表达式,则返回true,否则返回false。

因此,通过使用MustCompile和MatchString函数,我们可以验证任何字符串以检查是否为字母数字。因此,我们可以进一步使用条件语句以相应地打印消息。

// Golang程序检查字母数字正则表达式
package main
import (
    "fmt"
    "regexp"
)
func main() {
    var word string
    fmt.Print("输入一个字符串: ")
    fmt.Scan(&word)
    is_alphanumeric := regexp.MustCompile(`^[a-zA-Z0-9]*$`).MatchString(word)
    fmt.Print(is_alphanumeric)
    if is_alphanumeric{
        fmt.Printf("%s是字母数字字符串", word)
    } else{
        fmt.Printf("%s不是字母数字字符串", word)
    }
} 
Go

输出: 因此,脚本按预期工作,并为不同的字符串组合提供适当的输出。

Golang 检查字符串是否为字母数字

将脚本转换为函数

我们可以将上述脚本转换为函数,以便无论项目的要求和条件如何,都可以更好地使用。

// Go语言程序检查字母数字字符串
package main
 
import (
    "fmt"
    "regexp"
)
 
func is_alphanum(word string) bool {
    return regexp.MustCompile(`^[a-zA-Z0-9]*$`).MatchString(word)
}
 
func main() {
    var word string
    fmt.Print("输入任意字符串: ")
    fmt.Scan(&word)
    is_alphanumeric := is_alphanum(word)
    if is_alphanumeric{
        fmt.Printf("%s 是字母数字字符串", word)
    } else{
        fmt.Printf("%s 不是字母数字字符串", word)
    }
} 
Go

输出:

Golang 检查字符串是否为字母数字

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册