Go语言学习——正则表达式

正则表达式规则:
Go语言学习——正则表达式_第1张图片
示例代码:

package main

import (
    "fmt"
    "regexp"
)

func main() {
	str := "880218end"
	match, _ := regexp.MatchString("\\d{6}", str) //六位连续的数字
	fmt.Println(match)    //输出true
	reg := regexp.MustCompile("\\d{6}")
	//返回str中第一个匹配reg的字符串
	data := reg.Find([]byte(str))
	fmt.Println(string(data))  //880218
	//go语言正则表达式判断是否为汉字
	matchChinese, _ := regexp.Match("[\u4e00-\u9fa5]", []byte("经度"))
	fmt.Println(matchChinese)       //输出true
	//go语言正则表达式判断是否含有字符(大小写)
	matchChar, _ := regexp.Match("[a-zA-Z]", []byte("av132"))
	fmt.Println(matchChar)         //输出false
	//go语言正则表达式判断是否含有以数字开头,不是为true
	matchDigit, _ := regexp.Match(`[^\d]`, []byte("as132"))
	fmt.Println(matchDigit)         //输出true
	//go语言正则表达式判断是否含有为IP地址
	ip := "10.32.12.01"
	pattern := "[\\d]+\\.[\\d]+\\.[\\d]+\\.[\\d]+"
	matchIp, _ := regexp.MatchString(pattern, ip)
	fmt.Println(matchIp)          //输出true
	//go语言正则表达式判断是否包含某些字段
	id := "id=123;dfg"
	reg := regexp.MustCompile("id=[\\d]+")
	MEId := reg.FindString(id)
	fmt.Println(MEId)         //输出id=123
	//go语言正则表达式找出字符串中包含的所有的某些字段
	ss:=`
	tt=4.9911%,UE1,Sym1
	tt=3.6543%,UE1,Sym2
	tt=3.6133%,UE1,Sym3
	tt=3.263%,UE1,Sym4
	tt=3.3032%,UE1,Sym5
	tt=3.597%,UE1,Sym6
	tt=4.0367%,UE1,Sym7
	tt=3.2444%,UE1,Sym8
	tt=3.5291%,UE1,Sym9
	tt=3.4419%,UE1,Sym10
	tt=3.1114%,UE1,Sym11
	tt=3.5851%,UE1,Sym12
	`
	reg := regexp.MustCompile("tt=[\\d.\\d]+")
	tt := reg.FindAllString(ss, -1)//填写-1,就可以全部找出来
	fmt.Println(tt)//打印结果[tt=4.9911 tt=3.6543 tt=3.6133 tt=3.263 tt=3.3032 tt=3.597 tt=4.0367 tt=3.2444 tt=3.5291 tt=3.4419 tt=3.1114 tt=3.5851 tt=3.6432]
	//提取字符串中特殊的子字符串
	s1:="肖申克的救赎"
	reg := regexp.MustCompile(`(.*?)`)
	items := reg.FindAllStringSubmatch(s1, -1)
	fmt.Println(items[0][1])//肖申克的救赎
}

你可能感兴趣的:(Go语言学习历程)