go中的正则表达:Regexp标准库

115 阅读1分钟

参数说明:

  • pattern:要查找的正则表达式
  • matched:返回是否找到匹配项,布尔类型
  • re *Regexp:go正则匹配实例对象

正则表达式语法

常用函数

1. func Match(pattern string, b []byte)(matchd bool, err error)

检查b中是否存在匹配pattern的子序列(连续的)

package main

import (
	"fmt"
	"regexp"
)

func main() {
	matched, err := regexp.Match(`foo*`, []byte(`seafood`))
	fmt.Println(matched, err)
}

2. func MatchString(pattern string, s string) (matched bool, err error)

检查字符串S是否匹配pattern

package main

import (
	"fmt"
	"regexp"
)

func main() {
	matched, err := regexp.MatchString("foo.*", "seafood")
	fmt.Println(matched, err)
}

3. func Compile(expr string) (*Regexp, error)

解析并且在匹配过程中选择回溯搜索到的第一个匹配结果,如果成功返回,该Regexp就可用于匹配文本。

package main

import (
	"regexp"
)

func main() {
	compile, err := regexp.Compile(`^(.{6,16}[^0-9]*[^A-Z]*[^a-z]*[a-zA-Z0-9]*)$`)
}

4. func MustCompile(pattern string, s string) (matched bool, err error)

类似Compile但会在解析失败时panic,主要用于全局正则表达式变量的安全初始化。

package main

import (
	"regexp"
)

func main() {
	compile, err := regexp.MustCompile(`^(.{6,16}[^0-9]*[^A-Z]*[^a-z]*[a-zA-Z0-9]*)$`)
}

5. func (re *Regexp) Find(b []byte) []byte

返回正则表达式re在b中的最左侧的一个匹配结果的[]byte切片。如果没有匹配到,会返回nil。

package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile(`foo.?`)
	fmt.Printf("%q\n", re.Find([]byte(`seafood fool`)))

}

参考--go 正则函数

参考--# GO:Regexp正则操作