go regexp

正则是任何语言都必备的工具,这里介绍golang的使用方法

使用"

1
regexp.Compile("[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+")

使用 ```

1
regexp.Compile(`[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+`)

基础应用

查询是否存在,返回true/false

1
2
3
4
5
6
7
8
import "fmt"
import "regexp"

func main() {
a,b := regexp.MatchString(`\/(.*?)\?`,"/abc?a=1")
fmt.Printf("%s%s.\n", a,b)
// output: %!s(bool=true)%!s(<nil>).
}

查找字符串全部结果并返回查询结果
※ 查询单个结果使用 FindStringSubmatch

1
2
3
4
5
6
7
8
9
10
11
r,_ := regexp.Compile(`\/(.*?)\?`)
a := r.FindAllStringSubmatch("/abc?a=1", -1)
fmt.Println(a)

d,_ := regexp.Compile(`e(d\S{1})`)
e := d.FindAllStringSubmatch("abceedcwefedwedc", -1)
fmt.Println(e)

// output
// [[/abc? abc]]
// [[edc dc] [edw dw] [edc dc]]

动态匹配

1
2
3
4
5
6
7
8
h := fmt.Sprintf(`e(%s\S{1})`, f)
fmt.Println(h) // output: e(ee\S{1})

j,_ := regexp.Compile(h)
k := j.FindAllStringSubmatch("bbbeeefff", -1)
fmt.Println(k)

// output: [[eeef eef]]
#

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×