知識點 正則

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()
相關文章
相關標籤/搜索