golang中正则表达式的操作可以用regexp包提供的方法。
————————————————————
// 判断在 b 中能否找到正则表达式 pattern 所匹配的子串
// pattern:要查找的正则表达式
// b:要在其中进行查找的 []byte
// matched:返回是否找到匹配项
// err:返回查找过程中遇到的任何错误
// 此函数通过调用 Regexp 的方法实现
func Match(pattern string, b []byte) (matched bool, err error)
func main() {
fmt.Println(regexp.Match("H.* ", []byte("Hello World!")))
// true
}
————————————————————
// 判断在 r 中能否找到正则表达式 pattern 所匹配的子串
// pattern:要查找的正则表达式
// r:要在其中进行查找的 RuneReader 接口
// matched:返回是否找到匹配项
// err:返回查找过程中遇到的任何错误
// 此函数通过调用 Regexp 的方法实现
func MatchReader(pattern string, r io.RuneReader) (matched bool, err error)
func main() {
r := bytes.NewReader([]byte("Hello World!"))
fmt.Println(regexp.MatchReader("H.* ", r))
// true
}
————————————————————
// 判断在 s 中能否找到正则表达式 pattern 所匹配的子串
// pattern:要查找的正则表达式
// r:要在其中进行查找的字符串
// matched:返回是否找到匹配项
// err:返回查找过程中遇到的任何错误
// 此函数通过调用 Regexp 的方法实现
func MatchString(pattern string, s string) (matched bool, err error)
func main() {
fmt.Println(regexp.Match("H.* ", "Hello World!"))
// true
}
————————————————————
// QuoteMeta 将字符串 s 中的“特殊字符”转换为其“转义格式”
// 例如,QuoteMeta(`[foo]`)返回`\[foo\]`。
// 特殊字符有:\.+*?()|[]{}^$
// 这些字符用于实现正则语法,所以当作普通字符使用时需要转换
func QuoteMeta(s string) string
func main() {
fmt.Println(regexp.QuoteMeta("(?P:Hello) [a-z]"))
// \(\?P:Hello\) \[a-z\]
}
————————————————————
// Regexp 结构表示一个编译后的正则表达式
// Regexp 的公开接口都是通过方法实现的
// 多个 goroutine 并发使用一个 RegExp 是安全的
type Regexp struct {
// 私有字段
}
// 通过 Complite、CompilePOSIX、MustCompile、MustCompilePOSIX
// 四个函数可以创建一个 Regexp 对象
————————————————————
// Compile 用来解析正则表达式 expr 是否合法,如果合法,则返回一个 Regexp 对象
// Regexp 对象可以在任意文本上执行需要的操作
func Compile(expr string) (*Regexp, error)
func main() {
reg, err := regexp.Compile(`\w+`)
fmt.Printf("%q,%v\n", reg.FindString("Hello World!"), err)
// "Hello",
}
————————————————————
// CompilePOSIX 的作用和 Compile 一样
// 不同的是,CompilePOSIX 使用 POSIX 语法,
// 同时,它采用最左最长方式搜索,
// 而 Compile 采用最左最短方式搜索
// POSIX 语法不支持 Perl 的语法格式:\d、\D、\s、\S、\w、\W
func CompilePOSIX(expr string) (*Regexp, error)
func main() {
reg, err := regexp.CompilePOSIX(`[[:word:]]+`)
fmt.Printf("%q,%v\n", reg.FindString("Hello World!"), err)
// "Hello"
}
————————————————————
// MustCompile 的作用和 Compile 一样
// 不同的是,当正则表达式 str 不合法时,MustCompile 会抛出异常
// 而 Compile 仅返回一个 error 值
func MustCompile(str string) *Regexp
func main() {
reg := regexp.MustCompile(`\w+`)
fmt.Println(reg.FindString("Hello World!"))
// Hello
}
————————————————————
// MustCompilePOSIX 的作用和 CompilePOSIX 一样
// 不同的是,当正则表达式 str 不合法时,MustCompilePOSIX 会抛出异常
// 而 CompilePOSIX 仅返回一个 error 值
func MustCompilePOSIX(str string) *Regexp
func main() {
reg := regexp.MustCompilePOSIX(`[[:word:]].+ `)
fmt.Printf("%q\n", reg.FindString("Hello World!"))
// "Hello "
}
————————————————————
// 在 b 中查找 re 中编译好的正则表达式,并返回第一个匹配的内容
func (re *Regexp) Find(b []byte) []byte
func main() {
reg := regexp.MustCompile(`\w+`)
fmt.Printf("%q", reg.Find([]byte("Hello World!")))