golang 正則匹配語法及示例

2021-09-26 06:43:20 字數 1609 閱讀 5477

字串處理我們可以使用strings包來進行搜尋(contains、index)、替換(replace)和解析(split、join)等操作,但是這些都是簡單的字串操作,他們的搜尋都是大小寫敏感,而且固定的字串,如果我們需要匹配可變的那種就沒辦法實現了,當然如果strings包能解決你的問題,那麼就盡量使用它來解決。因為他們足夠簡單、而且效能和可讀性都會比正則好。

標題你過來啊

hello mike

你大爺呵呵

`//(.*?)被括起來的表示式作為分組

//匹配***

模式的所有子串

exp2 := regexp.mustcompile(`(.*?)

`)result2 := exp2.findallstringsubmatch(context2, -1)

//[[你過來啊

你過來啊] [hello mike

hello mike] [你大爺

你大爺]]

fmt.printf("%v\n", result2)

fmt.printf("\n------------------------------------\n\n")

context3 := `

標題你過來啊

hello

mike

go你大爺呵呵`

exp3 := regexp.mustcompile(`(.*?)

`)result3 := exp3.findallstringsubmatch(context3, -1)

//[[你過來啊

你過來啊] [你大爺

你大爺]]

fmt.printf("%v\n", result3)

fmt.printf("\n------------------------------------\n\n")

context4 := `

標題你過來啊

hello

mike

go你大爺呵呵`

exp4 := regexp.mustcompile(`(?s:(.*?))

`)  //讓 . 匹配 \n (預設為 false)

result4 := exp4.findallstringsubmatch(context4, -1)

/*[[你過來啊

你過來啊] [hello

mike

go hello

mike

go] [你大爺

你大爺]]

*/fmt.printf("%v\n", result4)

fmt.printf("\n------------------------------------\n\n")

for _, text := range result4

}

Golang爬蟲及正規表示式的實現示例

目錄 最近學習go,爬取 資料用到正規表示式,做個總結 go中正規表示式採用re2語法 具體是啥咱也不清楚 方法 引數正則字串,返回值 regexp str regexp.mustcompile string 引數要查詢的資料,查詢次數 1為全域性,返回值二維陣列,查詢出的字串 正則字串 var r...

MongoDB聚合語法及示例

mongodb中聚合的方法使用aggregate mongodb中聚合 aggregate 主要用於處理資料 諸如統計平均值,求和等 並返回計算後的資料結果。語法 db.collection name.aggregate aggregate operation 示例集合中的資料如下 現在我們通過以上...

正規表示式匹配示例

正規表示式示例 表示式匹配 s 匹配空行。d d 驗證由兩位數字 乙個連字元再加 5 位數字組成的 id 號。s s s s s s 1 s 匹配 html 標記。下表包含了元字元的完整列表以及它們在正規表示式上下文中的行為 字元說明 將下一字元標記為特殊字元 文字 反向引用或八進位制轉義符。例如,...