2023-08-22|閱讀時間 ‧ 約 5 分鐘

Golang 正則進階篇 (一):正則語法加強版

歡迎來到本系列的第一篇文章!你還記得我們之前聊過的

用 Golang 玩玩正則表達式 嗎?

今天,我們要走得更遠,深入 Go 語言。在這一篇中,我們將深入探討 Golang 正則表達式的高級技巧,讓你能夠更自信地處理各種複雜的文本/字串匹配和處理任務。


貪婪與非貪婪匹配

解釋貪婪匹配和非貪婪匹配的概念。

案例:

假設你有一段 HTML 代碼,你想提取出所有的超連結文本。使用正則表達式 href="(.*?)" 來實現非貪婪匹配,這樣可以確保只抓取每個超連結的 URL。
package main

import (
"fmt"
"regexp"
)

func main() {
html := `<a href="https://www.example.com">Link 1</a> <a href="https://www.example2.com">Link 2</a>`
re := regexp.MustCompile(`href="(.*?)"`)
matches := re.FindAllStringSubmatch(html, -1)

for _, match := range matches {
fmt.Println(match[1])
}
}


分組與捕獲

深入了解正則表達式中的分組機制。

案例:

假設你有一個日期字符串,你想從中提取年份和月份,但你只關心月份。使用正則表達式 (?:\d{4})-(\d{2})-\d{2} 來進行非捕獲分組,這樣你只捕獲到月份部分。
package main

import (
"fmt"
"regexp"
)

func main() {
dateStr := "2023-08-22"
re := regexp.MustCompile(`(?:\d{4})-(\d{2})-\d{2}`)
match := re.FindStringSubmatch(dateStr)

if len(match) > 1 {
fmt.Println("Month:", match[1])
}
}


正則表達式中的 OR 邏輯

解釋正則表達式中的 OR 邏輯如何構建和使用。

案例:

假設你要解析一個文本文件,其中包含不同單詞的拼寫變體。你希望捕獲所有包含 "color" 或 "colour" 的單詞。你可以使用正則表達式 \b(colou?r)\b 來實現這一目標。
package main

import (
"fmt"
"regexp"
)

func main() {
text := "colorful colours color"
re := regexp.MustCompile(`\b(colou?r)\b`)
matches := re.FindAllStringSubmatch(text, -1)

for _, match := range matches {
fmt.Println(match[1])
}
}


性能優化技巧

解釋避免回溯的重要性和影響。

案例:

假設你需要從一大段文本中匹配多個關鍵詞,使用惰性限定符可以優化匹配性能。
package main

import (
"fmt"
"regexp"
)

func main() {
text := "keyword1 something keyword2 another keyword3"
keywords := []string{"keyword1", "keyword2", "keyword3"}

for _, keyword := range keywords {
re := regexp.MustCompile(keyword)
if re.MatchString(text) {
fmt.Println("Found:", keyword)
}
}
}


小結

本篇文章中,我們已經深入學習了正則表達式的高級技巧,包括非貪婪匹配、分組與捕獲、OR 邏輯以及性能優化技巧。這些技巧將使你在處理文本匹配時更加靈活和高效。經過這篇文章的學習,你已經準備好在下一篇

Golang 正則進階篇 (二):實際應用

將這些知識應用到實際的文本處理任務中了。

分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.