go中正则表达式使用
文章目录
一、简介
这里介绍在go中使用正则表达式。
二、知识点
2.1 正则表达式模块regexp
go中正则表达式依赖模块为regexp,编码中引入示例如下:
import (
"regexp"
)
2.1 预编译语法
go中正则表达式依赖模块为regexp,正则表达式预编译方法主要有:Compile、MustCompile、CompilePOSIX、MustCompilePOSIX。
2.1.1 Compile
Compile方法,返回结果包含err字段,采用最左最短方式搜索,源码定义如下:
func Compile(expr string) (*Regexp, error) {
}
使用示例:
reg, _ := regexp.Compile(`<.*?>`)
2.1.2 MustCompile
MustCompile同Compile一样,只是返回结果没有err字段,出错时直接抛异常,源码定义如下:
func MustCompile(str string) *Regexp {
}
使用示例:
mustReg := regexp.MustCompile(`<.*?>`)
2.1.3 CompilePOSIX
CompilePOSIX同Compile类似,预编译正则表达式,采用posix语法,最左最长方式搜索,不支持\w,\W等perl写法,源码定义如下:
func CompilePOSIX(expr string) (*Regexp, error) {
}
使用示例:
posixReg, _ := regexp.CompilePOSIX(`<.*?>`)
2.1.4 MustCompilePOSIX
MustCompilePOSIX同CompilePOSIX类似,只是返回结果没有err字段,出错时直接抛异常,源码定义如下:
func MustCompilePOSIX(str string) *Regexp {
}
使用示例:
mustPosixReg