做数据新闻的网站,第一推广网,加强社区网站建设,图片字体转wordpress1. 数据验证
正则表达可用于验证文本是否满足某种给定的模式。
正则表达式也是一种语言#xff0c;因此在使用之前必须先对其进行编译#xff0c;并将编译结果保存在一个Regexp类型的变量里。以下两个函数即返回该变量的指针。
re, err : regexp.Compile(^[a-zA-Z0-…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函数少了一个参数。
// 数据验证
// 正则表达可用于验证文本是否满足某种给定的模式
// 正则表达式 regexp.MustCompile(模式)
// 验证通过 正则表达式.MatchString(被验证文本)
package main
import (fmtregexp
)
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 - trueiamthebestuseofthisappevaaaar - 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
先根据正则表达式对数据进行评估检查其中是否含有非法字符。如果含有非法字符再根据正则表达式将其替换为合法字符——数据清洗管道。
// 数据变换
// 正则表达可对文本中符合特定模式的内容进行替换
// 正则表达式 regexp.MustCompile(模式)
// 正则表达式.ReplaceAllString(被替换文本, 替换文本)
package mainimport (fmtregexp
)func main() {usernames : [...]string{slimshady99,!asdf£33£3,roger,iamthebestuseofthisappevaaaar,}re : regexp.MustCompile( // 定义正则表达1^[a-zA-Z0-9]{5,12}$)an : regexp.MustCompile([[:^alnum:]])//定义用于数据替换的正则表达式2for _, username : range usernames {newUsername : usernameif len(newUsername) 12 { // 首先判断用户名是否符合长度要求newUsername newUsername[:12] // 不符合的直接截断}if !re.MatchString(newUsername) { // 检查用户名是否符合正则表达式1要求newUsername an.ReplaceAllString( // 将所有非法字符替换为xnewUsername, x)}fmt.Println(username, -, newUsername)}
}
// 打印输出
slimshady99 - slimshady99
!asdf£33£3 - xasdfx33x3
roger - roger
iamthebestuseofthisappevaaaar - iamthebestus //截断