Go中regexp包常見的正則表達(dá)式操作
在 Golang 中,regexp 包用于處理正則表達(dá)式操作。以下是一些常見的正則表達(dá)式操作的代碼示例:
1. 簡(jiǎn)單匹配(MatchString)
用于檢查字符串是否匹配某個(gè)正則表達(dá)式。
package main
import (
"fmt"
"regexp"
)
func main() {
pattern := `^hello`
text := "hello world"
match, _ := regexp.MatchString(pattern, text)
fmt.Println("Matched:", match) // 輸出: Matched: true
}
2. 編譯正則表達(dá)式(Compile 和 MustCompile)
通過(guò) regexp.Compile 或 regexp.MustCompile 編譯正則表達(dá)式以提高性能。
package main
import (
"fmt"
"regexp"
)
func main() {
// Compile 返回 error,如果正則無(wú)效
re, err := regexp.Compile(`\d+`)
if err != nil {
fmt.Println("Error compiling regex:", err)
return
}
text := "Order number 12345"
fmt.Println("Matched:", re.MatchString(text)) // 輸出: Matched: true
// MustCompile 會(huì) panic,如果正則無(wú)效
re2 := regexp.MustCompile(`\d+`)
fmt.Println("Matched:", re2.MatchString(text)) // 輸出: Matched: true
}
3. 查找字符串中的第一個(gè)匹配項(xiàng)(FindString 和 FindStringSubmatch)
FindString返回第一個(gè)匹配的字符串。FindStringSubmatch返回第一個(gè)匹配的字符串以及捕獲的子組。
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`(\d+)-(\d+)-(\d+)`)
text := "Today's date is 2025-01-25."
// 找到第一個(gè)匹配的字符串
match := re.FindString(text)
fmt.Println("Found:", match) // 輸出: Found: 2025-01-25
// 找到第一個(gè)匹配及其子組
submatches := re.FindStringSubmatch(text)
fmt.Println("Submatches:", submatches) // 輸出: Submatches: [2025-01-25 2025 01 25]
}
4. 查找所有匹配項(xiàng)(FindAllString 和 FindAllStringSubmatch)
FindAllString返回所有匹配的字符串。FindAllStringSubmatch返回所有匹配的字符串及其子組。
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`\d+`)
text := "Numbers: 123, 456, and 789."
// 找到所有匹配的字符串
matches := re.FindAllString(text, -1)
fmt.Println("Matches:", matches) // 輸出: Matches: [123 456 789]
// 限制返回的匹配數(shù)量
limitedMatches := re.FindAllString(text, 2)
fmt.Println("Limited Matches:", limitedMatches) // 輸出: Limited Matches: [123 456]
}
5. 替換字符串(ReplaceAllString)
用于替換所有匹配的字符串。
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`\d+`)
text := "Order 123, 456, and 789."
// 替換所有匹配的數(shù)字為 XXX
result := re.ReplaceAllString(text, "XXX")
fmt.Println("Replaced:", result) // 輸出: Replaced: Order XXX, XXX, and XXX.
}
6. 替換字符串(ReplaceAllStringFunc)
通過(guò)一個(gè)函數(shù)動(dòng)態(tài)替換匹配的字符串。
package main
import (
"fmt"
"regexp"
"strings"
)
func main() {
re := regexp.MustCompile(`[a-z]+`)
text := "hello world GO!"
// 將匹配的字符串替換為大寫
result := re.ReplaceAllStringFunc(text, strings.ToUpper)
fmt.Println("Replaced:", result) // 輸出: Replaced: HELLO WORLD GO!
}
7. 分割字符串(Split)
使用正則表達(dá)式分割字符串。
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`\s+`) // 匹配空白字符
text := "Split this string!"
// 分割字符串
parts := re.Split(text, -1)
fmt.Println("Parts:", parts) // 輸出: Parts: [Split this string!]
}
8. 提取子組并命名(Named Captures)
通過(guò)命名捕獲組提取特定的子組。
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`(?P<Year>\d{4})-(?P<Month>\d{2})-(?P<Day>\d{2})`)
text := "Date: 2025-01-25."
// 提取所有子組
submatches := re.FindStringSubmatch(text)
fmt.Println("Submatches:", submatches) // 輸出: Submatches: [2025-01-25 2025 01 25]
// 提取命名的子組
names := re.SubexpNames()
for i, name := range names {
if name != "" {
fmt.Printf("%s: %s\n", name, submatches[i])
}
}
// 輸出:
// Year: 2025
// Month: 01
// Day: 25
}
9. 檢查字符串起始位置匹配(MatchString 和 Match)
MatchString檢查整個(gè)字符串。Match檢查字節(jié)切片。
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`^hello`)
text := "hello world"
bytes := []byte("hello bytes")
fmt.Println("String Match:", re.MatchString(text)) // 輸出: String Match: true
fmt.Println("Bytes Match:", re.Match(bytes)) // 輸出: Bytes Match: true
}
10. 替換字節(jié)切片(ReplaceAll)
與字符串操作類似,但作用于字節(jié)切片。
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`\d+`)
text := []byte("Order 123, 456, and 789.")
// 替換所有匹配的數(shù)字為 XXX
result := re.ReplaceAll(text, []byte("XXX"))
fmt.Println("Replaced:", string(result)) // 輸出: Replaced: Order XXX, XXX, and XXX.
}到此這篇關(guān)于Go中regexp包常見的正則表達(dá)式操作的文章就介紹到這了,更多相關(guān)Go regexp正則表達(dá)式操作內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于Golang實(shí)現(xiàn)統(tǒng)一加載資源的入口
當(dāng)我們需要在?main?函數(shù)中做一些初始化的工作,比如初始化日志,初始化配置文件,都需要統(tǒng)一初始化入口函數(shù),所以本文就來(lái)編寫一個(gè)統(tǒng)一加載資源的入口吧2023-05-05
Golang標(biāo)準(zhǔn)庫(kù)之errors包應(yīng)用方式
Go語(yǔ)言的errors包提供了基礎(chǔ)的錯(cuò)誤處理能力,允許通過(guò)errors.New創(chuàng)建自定義error對(duì)象,error在Go中是一個(gè)接口,通過(guò)實(shí)現(xiàn)Error方法來(lái)定義錯(cuò)誤文本,對(duì)錯(cuò)誤的比較通?;趯?duì)象地址,而非文本內(nèi)容,因此即使兩個(gè)錯(cuò)誤文本相同2024-10-10
Go語(yǔ)言中實(shí)現(xiàn)完美錯(cuò)誤處理實(shí)踐分享
Go?語(yǔ)言是一門非常流行的編程語(yǔ)言,由于其高效的并發(fā)編程和出色的網(wǎng)絡(luò)編程能力,越來(lái)越受到廣大開發(fā)者的青睞。本文我們就來(lái)深入探討一下Go?語(yǔ)言中的錯(cuò)誤處理機(jī)制吧2023-04-04
Go語(yǔ)言RPC Authorization進(jìn)行簡(jiǎn)單ip安全驗(yàn)證的方法
這篇文章主要介紹了Go語(yǔ)言RPC Authorization進(jìn)行簡(jiǎn)單ip安全驗(yàn)證的方法,實(shí)例分析了Go語(yǔ)言進(jìn)行ip驗(yàn)證的技巧,需要的朋友可以參考下2015-03-03
golang遍歷處理map時(shí)的常見性能陷阱與解決方法
這篇文章主要為大家詳細(xì)介紹了Golang中有關(guān)循環(huán)處理map時(shí)的性能優(yōu)化,本文主要介紹了常見的三種場(chǎng)景,文中的示例代碼講解詳細(xì),需要的可以了解下2025-05-05
Go語(yǔ)言中雙Token登錄系統(tǒng)的思路與實(shí)現(xiàn)詳解
在現(xiàn)代Web應(yīng)用中,身份認(rèn)證是保障系統(tǒng)安全的重要環(huán)節(jié),本文將介紹如何使用Go語(yǔ)言實(shí)現(xiàn)雙Token登錄系統(tǒng),文中的示例代碼講解詳細(xì),需要的可以了解下2025-07-07

