22.2 正则表达式-数据验证、数据变换

1. 数据验证

正则表达可用于验证文本是否满足某种给定的模式。

正则表达式也是一种语言,因此在使用之前必须先对其进行编译,并将编译结果保存在一个Regexp类型的变量里。以下两个函数即返回该变量的指针。

  • re, err := regexp.Compile("^a-zA-Z0-9{5,12}$")
    • 在正则表达式未通过编译时返回错误
  • re := regexp.MustCompile("^a-zA-Z0-9{5,12}$")
    • 在正则表达式未通过编译时引发恐慌

Regexp类型的MatchString方法根据其参数字符串与正则表达式是否匹配返回true或者false。当通过Regexp类型变量使用MatchString方法时,仅需提高1个被验证字符串即可,因为正则表达式已提前编译并保存在调用对象内部。

  • fmt.Println(username, "->", re.MatchString(username))

正则表达式已提前编译并保存在re内部,故该方法比regexp.MatchString函数少了一个参数。

Go 复制代码
// 数据验证
// 正则表达可用于验证文本是否满足某种给定的模式
// 正则表达式 = regexp.MustCompile(模式) 
// 验证通过 = 正则表达式.MatchString(被验证文本) 
package main
import (
    "fmt"
    "regexp"
)
func main() {
    usernames := [...]string{
        "slimshady99",
        "!asdf£33£3",
        "roger",
        "iamthebestuseofthisappevaaaar",
    }
	re := regexp.MustCompile(
        "^[a-zA-Z0-9]{5,12}$")

    for _, username := range usernames {
        fmt.Println(username, "->",
            re.MatchString(username))
    }
}
// 打印输出:
 slimshady99 -> true
 !asdf£33£3 -> false	// !
 roger -> true
 iamthebestuseofthisappevaaaar -> false 	// 字符数超过12

2. 数据变换

正则表达可对文本中符合特定模式的内容进行替换。

Regexp类型的ReplaceAllString方法接受两个参数,第一个参数为被替换文本,第二个参数为替换文本。该方法将被替换文本中与调用变量中的正则表达式匹配的部分替换为替换文本。

  • an := regexp.MustCompile("\[:\^alnum:]")
    • 匹配由非(^)英语字母(alphabet)和数字(number)组成的字符集中的任意一个字符。
    • :\^ASCII类名: 匹配"ASCII类"外的一个字符,"ASCII类"见附录的说明。
  • newUsername = an.ReplaceAllString(newUsername, "x")
    • 将newUsername中所有既非英语字母亦非数字的字符替换为"x"
    • 例如:!asdf£33£3 -> xasdfx33x3

先根据正则表达式对数据进行评估,检查其中是否含有非法字符。如果含有非法字符,再根据正则表达式将其替换为合法字符------数据清洗管道。

Go 复制代码
// 数据变换
// 正则表达可对文本中符合特定模式的内容进行替换
// 正则表达式 = regexp.MustCompile(模式) 
// 正则表达式.ReplaceAllString(被替换文本, 替换文本) 
package main

import (
    "fmt"
    "regexp"
)

func main() {
    usernames := [...]string{
        "slimshady99",
        "!asdf£33£3",
        "roger",
        "iamthebestuseofthisappevaaaar",
    }

	re := regexp.MustCompile(	//	定义正则表达1
        "^[a-zA-Z0-9]{5,12}$")

    an := regexp.MustCompile("[[:^alnum:]]")//定义用于数据替换的正则表达式2

    for _, username := range usernames {
        newUsername := username
        if len(newUsername) > 12 {	// 首先判断用户名是否符合长度要求
            newUsername = newUsername[:12]	// 不符合的直接截断
        }

        if !re.MatchString(newUsername) { // 检查用户名是否符合正则表达式1要求
            newUsername = an.ReplaceAllString(	// 将所有非法字符替换为x
                newUsername, "x")
        }
        fmt.Println(username, "->", newUsername)
    }
}
// 打印输出:
slimshady99 -> slimshady99
!asdf£33£3 -> xasdfx33x3
roger -> roger
iamthebestuseofthisappevaaaar -> iamthebestus //截断
相关推荐
妙码生花2 天前
从 PHP 到 AI + Golang,程序员自救转型手记(八):设计管理员模型、热重载配置
前端·后端·go
tyung3 天前
Go 手写 Wait-Free MPSC 无界队列:SwapPointer 实现多生产者无锁入队
后端·go
陈明勇4 天前
Go 1.26 新特性回顾:语言增强、工具升级与 Green Tea GC 默认启用
后端·go
妙码生花4 天前
从 PHP 到 AI + Golang,程序员自救转型手记(二):目录结构、初始化 GIT、设计并开发配置系统
前端·后端·go
leeyi4 天前
Deer-Go:字节 Deer-Flow 的 Go 移植,深度研究 Agent 全拆解
go·aigc·agent
Bolt5 天前
TypeScript 7.0 来了:当 tsc 用 Go 重写之后
javascript·typescript·go
Go_error5 天前
Datatypes:Go 轻松支持数据库JSON类型
后端·go
任沫6 天前
Agent之Function Call
javascript·人工智能·go
唐青枫6 天前
别再把 interface 当万能盒子:Go 接口从隐式实现到项目解耦
go
Jack207 天前
HarmonyOS开发中请求拦截器链:日志、认证、重试
编程语言