[Go] 正则表达式 示例
生活随笔
收集整理的這篇文章主要介紹了
[Go] 正则表达式 示例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
package mainimport "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?
?
官方教程:http://studygolang.com/static/pkgdoc/pkg/regexp.htm
轉載于:https://www.cnblogs.com/52php/p/7019314.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的[Go] 正则表达式 示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (转)无特征过狗一句话猥琐思路
- 下一篇: 第二阶段冲刺-个人总结09