Go xmas2020 學習筆記 13、Regular Expressions
阿新 • • 發佈:2022-04-11
課程地址 go-class-slides/xmas-2020 at trunk · matt4biz/go-class-slides (github.com)
主講老師 Matt Holiday
正則表示式參考資料
Syntax · google/re2 Wiki (github.com)
13-Regular Expressions
Simple string searches
func main() { test := "Here is $1 which is $2!" test = strings.ReplaceAll(test, "$1", "honey") test = strings.ReplaceAll(test, "$2", "tasty") fmt.Println(test) }
Here is honey which is tasty!
使用 \(strings\) 包進行簡單搜尋,對於複雜搜尋和驗證,謹慎使用 \(regexp\) 。
Location by regex
func main() { te := "aba abba abbba" re := regexp.MustCompile(`b+`) mm := re.FindAllString(te, -1) id := re.FindAllStringIndex(te, -1) fmt.Println(mm) fmt.Println(id) for _, d := range id { fmt.Println(te[d[0]:d[1]]) } up := re.ReplaceAllStringFunc(te, strings.ToUpper) fmt.Println(up) }
[b bb bbb]
[[1 2] [5 7] [10 13]]
b
bb
bbb
aBa aBBa aBBBa
FindAllString(te, -1)
返回匹配的字串切片。
FindAllStringIndex(te, -1)
返回匹配的字串位置,是切片的切片。
UUID validation
var uu = regexp.MustCompile(`^[[:xdigit:]]{8}-[[:xdigit:]]{4}-[1-5][[:xdigit:]]{3}-[89abAB][[:xdigit:]]{3}-[[:xdigit:]]{12}$`) var test = []string{ "072664ee-a034-4cc3-a2e8-9f1822c43bbb", "072664ee-a034-4cc3-a2e8-9f1822c43bbbb", // ^ 如果不加 ^ $ 匹配了前面的且忽略了後面的b "072664ee-a034-6cc3-a2e8-9f1822c43bbbb", "072664ee-a034-4cc3-C2e8-9f1822c43bbb", } func main() { for i, t := range test { if !uu.MatchString(t) { fmt.Println(i, t, "\tfails") } } }
1 072664ee-a034-4cc3-a2e8-9f1822c43bbbb fails
2 072664ee-a034-6cc3-a2e8-9f1822c43bbbb fails
3 072664ee-a034-4cc3-C2e8-9f1822c43bbb fails
Capture groups
var ph = regexp.MustCompile(`\(([[:digit:]]{3})\) ([[:digit:]]{3})-([[:digit:]]{4})`)
func main() {
orig := "(214) 514-9548"
match := ph.FindStringSubmatch(orig)
fmt.Printf("%q\n", match)
if len(match) > 3 {
fmt.Printf("+1 %s-%s-%s\n", match[1], match[2], match[3])
}
}
["(214) 514-9548" "214" "514" "9548"]
+1 214-514-9548
URL re
(?::([0-9]+))? 末尾的問號確定圓括號內的內容可以出現零次或一次。
?: 表示不被捕獲,即整個括號內容匹配了也不新增到返回的切片裡。
但內部又有一個捕獲組 ([0-9]+) 匹配出現一次或多次的數字,將被捕獲到字串放入返回的切片中。
所以 :([0-9]+) 這一整個不會出現在切片中,而 ([0-9]+) 會出現在切片中。
FindStringSubmatch
只會匹配最後一個,使用FindAllStringSubmatch
返回全部匹配,切片的切片。