Golang标准库(Regexp)正则匹配

Golang标准库(Regexp)正则匹配

简介

regexp包实现了golang中正则表达式搜索,详细内容请见文档

https://studygolang.com/static/pkgdoc/pkg/regexp.htm

工具

1、正则表达在线测试

https://c.runoob.com/front-end/854/

2、正则表达工具文档

https://www.runoob.com/regexp/regexp-syntax.html

常用库函数

1、func Compile

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

Compile解析并返回一个正则表达式。如果成功返回,该Regexp就可用于匹配文本。

在匹配文本时,该正则表达式会尽可能早的开始匹配,并且在匹配过程中选择回溯搜索到的第一个匹配结果。这种模式被称为“leftmost-first”,Perl、Python和其他实现都采用了这种模式,但本包的实现没有回溯的损耗。对POSIX的“leftmost-longest”模式,参见CompilePOSIX。

2、func MustCompile

func MustCompile(str string) *Regexp

func Comile增加了解析校验,若表达式解析失败,会panic,主要用于全局正则表达式变量的安全初始化

案例

实战:取出$space间的数据

package main

import (
	"fmt"
	"regexp"
)

func main() {
	buf := "$cpuload_useage31231%312 +$cpuloac_ppp /$disk_useage "
    //[^$]:不匹配$
    //*:匹配前一个字符0次或无限次,也就是除了$无限匹配次数
    //\w:相当于匹配[A-Za-z0-9]
	q :=regexp.MustCompile("[^$]*\\w")
	x := q.FindAllString(buf,10)
	fmt.Println(x)
	p := make(map[int]string)
	i:=1
	for _, metric := range x {
		p[i] = metric
		i++
	}
	fmt.Println(p)
}
上一篇:js日期格式化


下一篇:淘宝API、如何获取店铺详情店铺数据