https://blog.csdn.net/dhd040805/article/details/80259993
http://www.javashuo.com/article/p-ztrkpdie-hg.html先查看以上两篇文章
package main
import (
"fmt"
"regexp"
)
func main() {
reg, err := regexp.Compile("[a-z0-9#$%&]+")
if err != nil {
fmt.Println(err)
}
fmt.Println(reg.MatchString("AIh"))
fmt.Println(reg.MatchString("an82&#"))
}
运行结果:
false
true
第一个字符串AIh不匹配,第二个an82&#匹配。传入函数(re *Regexp) MatchString(s string) bool的字符串的每个字符都会被检验是否属于[a-z0-9#$%&]其中的一个,
a-z表示从小写a到小写z的26个英文字母,0-9表示从0到9的10个数字,#$%&是四个特殊字符,AIh中有两个大写字母,一个小写字母,h属于a-z,但字母A和I都不属于a-z,
也不属于0-9,也不属于特殊字符,因此第一个不匹配,只要一段内容中有一个字符不匹配[a-z0-9#$%&]+,就表示该段内容不匹配,中括号外面的加号+表示多个匹配,
即要求每个字符都属于小写字母或数字,或四个特殊字符中的一个;
[a-z0-7#$%&]去掉加号,表示某个字符串中只要有一个字符匹配,就表示匹配,每个字符都不匹配,才表示不匹配。
reg, err := regexp.Compile("[a-z0-7#$%&]")
if err != nil {
fmt.Println(err)
}
fmt.Println(reg.MatchString("AI"))
fmt.Println(reg.MatchString("an82&#"))
fmt.Println(reg.MatchString("A!+"))
fmt.Println(reg.MatchString("aA!+"))
fmt.Println(reg.MatchString(strconv.Itoa(8)))
fmt.Println(reg.MatchString(strconv.Itoa(789)))
运行结果:
false
true
false
true
false
true
regexp.MustCompile函数的用法
该函数比regexp.Compile少一个返回值error,除此以外用法同样
package main
import (
"fmt"
"regexp"
"strconv"
)
func main() {
s := "日本"
s2 := "中国"
s3 := "ad"
s4 := "G"
s5 := 9
s6 := 708
s7 := "@"
s8 := "国8h+¥œ"
s9 := "%"
s10 := "^"
ss := make([]string, 0)
ss = append(ss, s, s2, s3, s4, strconv.Itoa(s5), strconv.Itoa(s6), s7, s8, s9, s10)
reg := regexp.MustCompile("^[a-zA-Z0-8中国!@#&*+_¥œø]+$")
for k, v := range ss {
fmt.Println(k, v, reg.MatchString(v))
}
}
运行结果:
0 日本 false
1 中国 true
2 ad true
3 G true
4 9 false
5 708 true
6 @ true
7 国8h+¥œ true
8 % false
9 ^ false
函数Compile(expr string) (*Regexp, error)和MustCompile(str string) *Regexp的参数是正则表达式;
函数(re *Regexp) MatchString(s string) bool的参数是须要检验的内容,
匹配中文
正则表达式"^[a-zA-Z0-9\u4e00-\u9fa5]{3,8}$",匹配小写字母、大写字母、数字、或中文,长度3到8位。
package main
import (
"fmt"
"regexp"
)
func main() {
reg, err := regexp.Compile("^[a-zA-Z0-9\u4e00-\u9fa5]{3,8}$")
if err != nil {
fmt.Println(err)
}
fmt.Println(reg.MatchString("春暖花开"))
fmt.Println(reg.MatchString("春暖"))
fmt.Println(reg.MatchString("568"))
fmt.Println(reg.MatchString("aingege"))
fmt.Println(reg.MatchString("EIOGNE"))
fmt.Println(reg.MatchString("DIfin梅6"))
}
运行结果:
true
false
true
true
true
true
函数Compile和MustCompile传入参数时要写在英文双引号里面,不能够是单引号,也不能够是特殊字符 ` //待验证
package main
import "bytes"
import "fmt"
import "regexp"
func main() {
// 1. 这个测试一个字符串是否符合一个表达式。
match, _ := regexp.MatchString("p([a-z]+)ch", "peach")
fmt.Println("1.", match)
// 上面咱们是直接使用字符串,可是对于一些其余的正则任务,你须要使用 Compile 一个优化的 Regexp 结构体。
r, _ := regexp.Compile("p([a-z]+)ch")
// 2. 这个结构体有不少方法,这里是相似咱们前面看到的一个匹配测试。
fmt.Println("2.", r.MatchString("peach"))
// 3. 这是查找匹配字符串的。
fmt.Println("3.", r.FindString("peach punch"))
// 4. 这个也是查找第一次匹配的字符串的,可是返回的匹配开始和结束位置索引,而不是匹配的内容。
fmt.Println("4.", r.FindStringIndex("peach punch"))
// 5. Submatch 返回 彻底匹配 和 局部匹配 的字符串。例如,这里会返回 p([a-z]+)ch 和 ([a-z]+) 的信息。
fmt.Println("5.", r.FindStringSubmatch("peach punch"))
// 6. 相似的,这个会返回 彻底匹配 和 局部匹配 的索引位置。
fmt.Println("6.", r.FindStringSubmatchIndex("peach punch"))
// 7. 带 All 的这个函数返回全部的匹配项,而不只仅是首次匹配项。例如查找匹配表达式的全部项。
fmt.Println("7.", r.FindAllString("peach punch pinch", -1))
// 8. All 一样能够对应到上面的全部函数。
fmt.Println("8.", r.FindAllStringSubmatchIndex("peach punch pinch", -1))
// 9. 这个函数提供一个正整数来限制匹配次数。
fmt.Println("9.", r.FindAllString("peach punch pinch", 2))
// 10. 上面的例子中,咱们使用了字符串做为参数,并使用了如 MatchString 这样的方法。咱们也能够提供 []byte参数并将 String 从函数命中去掉。
fmt.Println("10.", r.Match([]byte("peach")))
// 11. 建立正则表示式常量时,可使用 Compile 的变体MustCompile 。由于 Compile 返回两个值,不能用语常量。
r = regexp.MustCompile("p([a-z]+)ch")
fmt.Println("11.", r)
// 12. regexp 包也能够用来替换部分字符串为其余值。
fmt.Println("12.", r.ReplaceAllString("a peach", "<fruit>"))
// 13. Func 变量容许传递匹配内容到一个给定的函数中,
in := []byte("a peach")
out := r.ReplaceAllFunc(in, bytes.ToUpper)
fmt.Println("13.", string(out))
}
运行结果:
1. true
2. true
3. peach
4. [0 5]
5. [peach ea]
6. [0 5 1 3]
7. [peach punch pinch]
8. [[0 5 1 3] [6 11 7 9] [12 17 13 15]]
9. [peach punch]
10. true
11. p([a-z]+)ch
12. a <fruit>
13. a PEACH
咱们指望在字符串 1000abcd123 中找出先后两个数字。
例子1:匹配到这个字符串的例子
package main
import(
"fmt"
"regexp"
)
var digitsRegexp = regexp.MustCompile(`(\d+)\D+(\d+)`)
func main(){
someString:="1000abcd123"
fmt.Println(digitsRegexp.FindStringSubmatch(someString))
}
上面代码输出:
[1000abcd123 1000 123]
例子2:使用带命名的正则表达式
package main
import(
"fmt"
"regexp"
)
var myExp=regexp.MustCompile(`(?P<first>\d+)\.(\d+).(?P<second>\d+)`)
func main(){
fmt.Printf("%+v",myExp.FindStringSubmatch("1234.5678.9"))
}
上面代码输出,全部匹配到的都输出了:
[1234.5678.9 1234 5678 9]
这里的Named capturing groups (?P<name>) 方式命名正则表达式是 python、Go语言特有的, java、c# 是 (?<name>) 命名方式。
例子3:对正则表达式类扩展一个得到全部命名信息的方法,并使用它。
package main
import(
"fmt"
"regexp"
)
//embed regexp.Regexp in a new type so we can extend it
type myRegexp struct{
*regexp.Regexp
}
//add a new method to our new regular expression type
func(r *myRegexp)FindStringSubmatchMap(s string) map[string]string{
captures:=make(map[string]string)
match:=r.FindStringSubmatch(s)
if match==nil{
return captures
}
for i,name:=range r.SubexpNames(){
//Ignore the whole regexp match and unnamed groups
if i==0||name==""{
continue
}
captures[name]=match[i]
}
return captures
}
//an example regular expression
var myExp=myRegexp{regexp.MustCompile(`(?P<first>\d+)\.(\d+).(?P<second>\d+)`)}
func main(){
mmap:=myExp.FindStringSubmatchMap("1234.5678.9")
ww:=mmap["first"]
fmt.Println(mmap)
fmt.Println(ww)
}
上面代码的输出结果:
map[first:1234 second:9]
1234
例子4,抓取限号信息,并记录到一个Map中。
package main
import(
"fmt"
iconv "github.com/djimenez/iconv-go"
"io/ioutil"
"net/http"
"os"
"regexp"
)
// embed regexp.Regexp in a new type so we can extend it
type myRegexp struct{
*regexp.Regexp
}
// add a new method to our new regular expression type
func(r *myRegexp)FindStringSubmatchMap(s string)[](map[string]string){
captures:=make([](map[string]string),0)
matches:=r.FindAllStringSubmatch(s,-1)
if matches==nil{
return captures
}
names:=r.SubexpNames()
for _,match:=range matches{
cmap:=make(map[string]string)
for pos,val:=range match{
name:=names[pos]
if name==""{
continue
}
/*
fmt.Println("+++++++++")
fmt.Println(name)
fmt.Println(val)
*/
cmap[name]=val
}
captures=append(captures,cmap)
}
return captures
}
// 抓取限号信息的正则表达式
var myExp=myRegexp{regexp.MustCompile(`自(?P<byear>[\d]{4})年(?P<bmonth>[\d]{1,2})月(?P<bday>[\d]{1,2})日至(?P<eyear>[\d]{4})年(?P<emonth>[\d]{1,2})月(?P<eday>[\d]{1,2})日,星期一至星期五限行机动车车牌尾号分别为:(?P<n11>[\d])和(?P<n12>[\d])、(?P<n21>[\d])和(?P<n22>[\d])、(?P<n31>[\d])和(?P<n32>[\d])、(?P<n41>[\d])和(?P<n42>[\d])、(?P<n51>[\d])和(?P<n52>[\d])`)}
func ErrorAndExit(err error){
fmt.Fprintln(os.Stderr,err)
os.Exit(1)
}
func main(){
response,err:=http.Get("http://www.bjjtgl.gov.cn/zhuanti/10weihao/index.html")
defer response.Body.Close()
if err!=nil{
ErrorAndExit(err)
}
input,err:=ioutil.ReadAll(response.Body)
if err!=nil{
ErrorAndExit(err)
}
body :=make([]byte,len(input))
iconv.Convert(input,body,"gb2312","utf-8")
mmap:=myExp.FindStringSubmatchMap(string(body))
fmt.Println(mmap)
}
上述代码输出:
[map[n32:0 n22:9 emonth:7 n11:3 n41:1 n21:4 n52:7 bmonth:4 n51:2 bday:9 n42:6 byear:2012 eday:7 eyear:2012 n12:8 n31:5]
map[emonth:10 n41:5 n52:6 n31:4 byear:2012 n51:1 eyear:2012 n32:9 bmonth:7 n22:8 bday:8 n11:2 eday:6 n42:0 n21:3 n12:7]
map[bday:7 n51:5 n22:7 n31:3 eday:5 n32:8 byear:2012 bmonth:10 emonth:1 eyear:2013 n11:1 n12:6 n52:0 n21:2 n42:9 n41:4]
map[eyear:2013 byear:2013 n22:6 eday:10 bmonth:1 n41:3 n32:7 n31:2 n21:1 n11:5 bday:6 n12:0 n51:4 n42:8 emonth:4 n52:9]]
这段代码首先下载北京市交管局的网页;而后把这个gb2312的页面转换成utf-8编码,而后用正则表达式提取其中的限号信息。
func ExampleRegexp_Split() {
a := regexp.MustCompile(`a`)
fmt.Println(a.Split("banana", -1))// [b n n ]
fmt.Println(a.Split("banana", 0)) // []
fmt.Println(a.Split("banana", 1)) // [banana]
fmt.Println(a.Split("banana", 2)) // [b nana]
zp := regexp.MustCompile(`z+`)
fmt.Println(zp.Split("pizza", -1)) // [pi a]
fmt.Println(zp.Split("pizza", 0)) // []
fmt.Println(zp.Split("pizza", 1)) // [pizza]
fmt.Println(zp.Split("pizza", 2)) // [pi a]
}html
func Example() {
// Compile the expression once, usually at init time.
// Use raw strings to avoid having to quote the backslashes.
var validID = regexp.MustCompile(`^[a-z]+\[[0-9]+\]$`)java
fmt.Println(validID.MatchString("adam[23]")) //true
fmt.Println(validID.MatchString("eve[7]")) //true
fmt.Println(validID.MatchString("Job[48]")) //false
fmt.Println(validID.MatchString("snakey")) //false
}python
// i : case insensitive
fmt.Println(regexp.MatchString(`abc`, "Abc")) //false
fmt.Println(regexp.MatchString(`(?i)abc`, "Abc")) //truegit
// m : multi-line mode: ^ and $ match begin/end line in addition to begin/end text
fmt.Println(regexp.MustCompile(`aaa$`).FindAllString("aaa\naaa", -1)) //[aaa]
fmt.Println(regexp.MustCompile(`(?m)aaa$`).FindAllString("aaa\naaa", -1)) //[aaa aaa]
// s : let . match \n
fmt.Println(regexp.MatchString(`^a.*b$`, "ab")) //true
fmt.Println(regexp.MatchString(`^a.*b$`, "a\nb")) //false
fmt.Println(regexp.MatchString(`(?s)^a.*b$`, "a\nb")) //truegithub
greedy := regexp.MustCompile(`a.+`)
nonGreedy := regexp.MustCompile(`a.+?`)
fmt.Println(greedy.FindString("abcd")) //abcd
fmt.Println(nonGreedy.FindString("abcd")) //ab正则表达式
greedy = regexp.MustCompile(`ab*`)
nonGreedy = regexp.MustCompile(`ab*?`)
fmt.Println(greedy.FindString("abbbb")) //abbbb
fmt.Println(nonGreedy.FindString("abbbb")) //aexpress
greedy = regexp.MustCompile(`(?U)ab*`)
nonGreedy = regexp.MustCompile(`(?U)ab*?`)
fmt.Println(greedy.FindString("abbbb")) //a
fmt.Println(nonGreedy.FindString("abbbb")) //abbbb
c#
//邮箱 最高30位
func (ic *RegexCheck) IsEmail(str ...string) bool {
var b bool
for _, s := range str {
b, _ = regexp.MatchString("^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$", s)
if false == b {
return b
}
}
return b
}
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:="<span class="title">肖申克的救赎</span>"
reg := regexp.MustCompile(`<span class="title">(.*?)</span>`)
items := reg.FindAllStringSubmatch(s1, -1)
fmt.Println(items[0][1])//肖申克的救赎
}
package main
import (
"bytes"
"fmt"
"regexp"
)
func main() {
//是否匹配字符串
// .匹配任意一个字符 ,*匹配零个或多个 ,优先匹配更多(贪婪)
match, _ := regexp.MatchString("H(.*)d!", "Hello World!")
fmt.Println(match) //true
//或
match, _ = regexp.Match("H(.*)d!", []byte("Hello World!"))
fmt.Println(match) //true
//或经过`Compile`来使用一个优化过的正则对象
r, _ := regexp.Compile("H(.*)d!")
fmt.Println(r.MatchString("Hello World!")) //true
// 这个方法返回匹配的子串
fmt.Println(r.FindString("Hello World! world")) //Hello World!
//同上
fmt.Println(string(r.Find([]byte("Hello World!")))) //Hello World!
// 这个方法查找第一次匹配的索引
// 的起始索引和结束索引,而不是匹配的字符串
fmt.Println(r.FindStringIndex("Hello World! world")) //[0 12]
// 这个方法返回全局匹配的字符串和局部匹配的字符,匹配最大的子字符串一次。
// 它和r.FindAllStringSubmatch("Hello World! world",1) 等价。 好比
// 这里会返回匹配`H(.*)d!`的字符串
// 和匹配`(.*)`的字符串
fmt.Println(r.FindStringSubmatch("Hello World! world")) //[Hello World! ello Worl]
// 和上面的方法同样,不一样的是返回全局匹配和局部匹配的
// 起始索引和结束索引
fmt.Println(r.FindStringSubmatchIndex("Hello World! world")) //[0 12 1 10]
// 这个方法返回全部正则匹配的字符,不只仅是第一个
fmt.Println(r.FindAllString("Hello World! Held! world", -1)) //[Hello World! Held!]
// 这个方法返回全部全局匹配和局部匹配的字符串起始索引,只匹配最大的串
// 和结束索引
fmt.Println(r.FindAllStringSubmatchIndex("Hello World! world", -1)) //[[0 12 1 10]]
fmt.Println(r.FindAllStringSubmatchIndex("Hello World! Held! world", -1)) //[[0 18 1 16]]
// 为这个方法提供一个正整数参数来限制匹配数量
res, _ := regexp.Compile("H([a-z]+)d!")
fmt.Println(res.FindAllString("Hello World! Held! Hellowrld! world", 2)) //[Held! Hellowrld!]
fmt.Println(r.FindAllString("Hello World! Held! world", 2)) //[Hello World! Held!]
//注意上面两个不一样,第二参数是一最大子串为单位计算。
// regexp包也能够用来将字符串的一部分替换为其余的值
fmt.Println(r.ReplaceAllString("Hello World! Held! world", "html")) //html world
// `Func`变量可让你将全部匹配的字符串都通过该函数处理
// 转变为所须要的值
in := []byte("Hello World! Held! world")
out := r.ReplaceAllFunc(in, bytes.ToUpper)
fmt.Println(string(out))
// 在 b 中查找 reg 中编译好的正则表达式,并返回第一个匹配的位置
// {起始位置, 结束位置}
b := bytes.NewReader([]byte("Hello World!"))
reg := regexp.MustCompile(`\w+`)
fmt.Println(reg.FindReaderIndex(b)) //[0 5]
// 在 字符串 中查找 r 中编译好的正则表达式,并返回全部匹配的位置
// {{起始位置, 结束位置}, {起始位置, 结束位置}, ...}
// 只查找前 n 个匹配项,若是 n < 0,则查找全部匹配项
fmt.Println(r.FindAllIndex([]byte("Hello World!"), -1)) //[[0 12]]
//同上
fmt.Println(r.FindAllStringIndex("Hello World!", -1)) //[[0 12]]
// 在 s 中查找 re 中编译好的正则表达式,并返回全部匹配的内容
// 同时返回子表达式匹配的内容
// {
// {完整匹配项, 子匹配项, 子匹配项, ...},
// {完整匹配项, 子匹配项, 子匹配项, ...},
// ...
// }
// 只查找前 n 个匹配项,若是 n < 0,则查找全部匹配项
reg = regexp.MustCompile(`(\w)(\w)+`) //[[Hello H o] [World W d]]
fmt.Println(reg.FindAllStringSubmatch("Hello World!", -1)) //[[Hello H o] [World W d]]
// 将 template 的内容通过处理后,追加到 dst 的尾部。
// template 中要有 $一、$二、${name1}、${name2} 这样的“分组引用符”
// match 是由 FindSubmatchIndex 方法返回的结果,里面存放了各个分组的位置信息
// 若是 template 中有“分组引用符”,则以 match 为标准,
// 在 src 中取出相应的子串,替换掉 template 中的 $一、$2 等引用符号。
reg = regexp.MustCompile(`(\w+),(\w+)`)
src := []byte("Golang,World!") // 源文本
dst := []byte("Say: ") // 目标文本
template := []byte("Hello $1, Hello $2") // 模板
m := reg.FindSubmatchIndex(src) // 解析源文本
// 填写模板,并将模板追加到目标文本中
fmt.Printf("%q", reg.Expand(dst, template, src, m))
// "Say: Hello Golang, Hello World"
// LiteralPrefix 返回全部匹配项都共同拥有的前缀(去除可变元素)
// prefix:共同拥有的前缀
// complete:若是 prefix 就是正则表达式自己,则返回 true,不然返回 false
reg = regexp.MustCompile(`Hello[\w\s]+`)
fmt.Println(reg.LiteralPrefix())
// Hello false
reg = regexp.MustCompile(`Hello`)
fmt.Println(reg.LiteralPrefix())
// Hello true
text := `Hello World! hello world`
// 正则标记“非贪婪模式”(?U)
reg = regexp.MustCompile(`(?U)H[\w\s]+o`)
fmt.Printf("%q\n", reg.FindString(text)) // Hello
// 切换到“贪婪模式”
reg.Longest()
fmt.Printf("%q\n", reg.FindString(text)) // Hello Wo
// 统计正则表达式中的分组个数(不包括“非捕获的分组”)
fmt.Println(r.NumSubexp()) //1
//返回 r 中的“正则表达式”字符串
fmt.Printf("%s\n", r.String())
// 在 字符串 中搜索匹配项,并以匹配项为分割符,将 字符串 分割成多个子串
// 最多分割出 n 个子串,第 n 个子串再也不进行分割
// 若是 n < 0,则分割全部子串
// 返回分割后的子串列表
fmt.Printf("%q\n", r.Split("Hello World! Helld! hello", -1)) //["" " hello"]
// 在 字符串 中搜索匹配项,并替换为 repl 指定的内容
// 若是 rep 中有“分组引用符”($一、$name),则将“分组引用符”当普通字符处理
// 所有替换,并返回替换后的结果
s := "Hello World, hello!"
reg = regexp.MustCompile(`(Hell|h)o`)
rep := "${1}"
fmt.Printf("%q\n", reg.ReplaceAllLiteralString(s, rep)) //"${1} World, hello!"
// 在 字符串 中搜索匹配项,而后将匹配的内容通过 repl 处理后,替换 字符串 中的匹配项
// 若是 repb 的返回值中有“分组引用符”($一、$name),则将“分组引用符”当普通字符处理
// 所有替换,并返回替换后的结果
ss := []byte("Hello World!")
reg = regexp.MustCompile("(H)ello")
repb := []byte("$0$1")
fmt.Printf("%s\n", reg.ReplaceAll(ss, repb))
// HelloH World!
fmt.Printf("%s\n", reg.ReplaceAllFunc(ss,
func(b []byte) []byte {
rst := []byte{}
rst = append(rst, b...)
rst = append(rst, "$1"...)
return rst
}))
// Hello$1 World!
}
小结
一、r, _ := regexp.Compile("H(.*)d!")
可用如下函数替代
r := regexp.MustCompile("H(.*)d!")
二者区别 MustCompile 少一个返回值err
二、regexp的处理byte的方法都有个string方法对应,二者功能同样。
例如regexp.Match()和regexp.MatchString()