网络推广收费价目表,seoaoo,手机创建网站免费注册,linux系统用wordpress前言
最近坐毕设ing#xff0c;简单的一个管理系统。 其中对于用户注册、登录功能#xff0c;需要进行一些参数校验。 因为之前使用过#xff0c;因此这里计划使用正则表达式进行校验。但是之前的使用也仅限于使用#xff0c;因此这次专门进行一次学习#xff0c;并做此记…前言
最近坐毕设ing简单的一个管理系统。 其中对于用户注册、登录功能需要进行一些参数校验。 因为之前使用过因此这里计划使用正则表达式进行校验。但是之前的使用也仅限于使用因此这次专门进行一次学习并做此记录。
什么是正则表达式
下面是菜鸟教程中给出的定义 正则表达式是一种用于匹配和操作文本的强大工具它是由一系列字符和特殊字符组成的模式用于描述要匹配的文本模式。 正则表达式可以在文本中查找、替换、提取和验证特定的模式。 简单来说他就是一个文字处理的工具对文字进行一系列的处理。在Golang中可以使用内置的regexp包来进行使用。
参数校验
使用MatchString
这里使用的是MatchString函数. // MatchString reports whether the string s
// contains any match of the regular expression pattern.
// More complicated queries need to use Compile and the full Regexp interface.
func MatchString(pattern string, s string) (matched bool, err error) {re, err : Compile(pattern)if err ! nil {return false, err}return re.MatchString(s), nil
}// Compile parses a regular expression and returns, if successful,
// a Regexp object that can be used to match against text.
//
// When matching against text, the regexp returns a match that
// begins as early as possible in the input (leftmost), and among those
// it chooses the one that a backtracking search would have found first.
// This so-called leftmost-first matching is the same semantics
// that Perl, Python, and other implementations use, although this
// package implements it without the expense of backtracking.
// For POSIX leftmost-longest matching, see CompilePOSIX.
func Compile(expr string) (*Regexp, error) {return compile(expr, syntax.Perl, false)
}// MatchString reports whether the string s
// contains any match of the regular expression re.
func (re *Regexp) MatchString(s string) bool {return re.doMatch(nil, nil, s)
}根据该函数的源码和注释可以看出其需要接受两个参数——校验规则pattern和待处理字符串s其返回两个值——matched 是一个布尔值表示是否匹配成功err 是一个错误值表示在匹配过程中是否出现了错误。
在函数内部它首先使用 Compile 函数将 pattern 编译成一个 Regexp 对象。如果编译过程中出现错误就会直接返回错误。如果编译成功它会调用编译后的 Regexp 对象的 MatchString 方法来对字符串 s 进行匹配最终将匹配结果返回。
校验规则
拿自己代码中用到的来举例 passwordPattern ^[a-zA-Z0-9]{6,12}$这个代表的是参数a-zA-Z0-9且长度在6-12位之间。 其他标识符规则如下 .: 匹配任意单个字符除了换行符。 *: 匹配前面的表达式零次或多次。 : 匹配前面的表达式一次或多次。 ?: 匹配前面的表达式零次或一次。 []: 字符类匹配括号内的任意一个字符。 |: 或操作符匹配两边任意一个表达式。 (): 分组用于将多个表达式组合在一起。 参考资源
本次学习主要参考自 Golang-regexp包官方文档 https://pkg.go.dev/regexp