Like Share Discussion Bookmark Smile

J.J. Huang   2025-06-29   Getting Started Golang 07.套件   瀏覽次數:次   DMCA.com Protection Status

Go | 正則套件的函式與介紹

💬 簡介

正則表達式(Regular Expression)是一種強大的字串處理工具,能快速完成搜尋、過濾與文字擷取等任務。
Go 語言的 regexp 套件內建對正則表達式的完整支援,讓我們可以在不依賴第三方工具的情況下,執行高效的字串處理。

本篇將介紹 regexp 套件的基礎用法與應用技巧,幫助你掌握如何在 Golang 中靈活運用正則。

圖片來源:Gophers


💡 基本用法:Match 檢查是否符合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package main

import (
"fmt"
"regexp"
)

func main() {
matched, err := regexp.MatchString(`^go+\d$`, "gooo1")
if err != nil {
panic(err)
}
fmt.Println("是否符合規則:", matched) // true
}

🧵 建立 Regexp 物件:Compile vs MustCompile

1
2
3
4
re, err := regexp.Compile(`[a-z]+@\w+\.\w+`)
if err != nil {
// 錯誤處理
}
1
re := regexp.MustCompile(`[a-z]+@\w+\.\w+`) // panic on error

📝 建議:開發時使用 Compile,若已確定正則無誤,正式環境可改用 MustCompile


🔍 實用函式總覽

函式 功能說明
MatchString(s) 判斷字串是否符合正則
FindString(s) 回傳第一個符合的子字串
FindAllString(s, -1) 回傳所有符合的子字串(無限筆)
FindStringSubmatch(s) 回傳整體匹配與分組結果(slice)
ReplaceAllString(s, r) 將符合的部分取代成指定字串
Split(s, n) 根據正則分割字串(n 為最大分割數)

🔨 範例:Email 擷取

1
2
3
4
5
6
7
8
9
10
11
12
13
package main

import (
"fmt"
"regexp"
)

func main() {
text := "聯絡信箱有 alice@mail.com、bob@dev.io 和 root@server.net"
re := regexp.MustCompile(`[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-z]{2,}`)
emails := re.FindAllString(text, -1)
fmt.Println("擷取的 Email:", emails)
}

🔨 範例:電話號碼格式化

1
2
3
4
5
6
7
8
9
10
11
12
13
package main

import (
"fmt"
"regexp"
)

func main() {
input := "聯絡電話: 0987-123-456"
re := regexp.MustCompile(`(\d{4})-(\d{3})-(\d{3})`)
formatted := re.ReplaceAllString(input, "$1 $2 $3")
fmt.Println("格式化後:", formatted)
}

🧰 補充技巧:分組與命名分組

  • 一般分組() 括號表示群組
  • 命名分組(Go 1.18+)
1
2
3
4
5
6
7
8
re := regexp.MustCompile(`(?P<user>\w+)@(?P<domain>\w+\.\w+)`)
match := re.FindStringSubmatch("admin@example.com")
names := re.SubexpNames()
for i, name := range names {
if i != 0 && name != "" {
fmt.Printf("%s = %s\n", name, match[i])
}
}

⚠️ 注意事項

  • Go 的 regexp 語法遵循 RE2,不支援 lookahead、lookbehind。
  • 建議將正則預編譯為物件(MustCompile),避免重複解析造成效能下降。
  • . 預設不包含換行,需搭配 (?s) 修飾符才支援跨行比對。

🎯 總結

regexp 套件讓 Golang 擁有原生且高效的正則處理能力:

  • ✅ 支援完整的正則語法與分組擷取
  • ✅ 提供 Find、Match、Replace、Split 多種操作介面
  • ✅ 適合字串驗證、資料清洗與擷取處理

只要熟悉其函式與正則語法,就能用極少程式碼完成複雜的文字處理邏輯,是 Golang 應用中不可或缺的利器!

最後建議回顧一下 Go | 菜鳥教學 目錄,了解其章節內容。


註:以上參考了
Go