欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Go中regexp包常見的正則表達式操作

 更新時間:2025年02月21日 10:10:12   作者:學(xué)亮編程手記  
本文主要介紹了Go中regexp包常見的正則表達式操作,包括匹配、查找、替換和分割字符串等,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

在 Golang 中,regexp 包用于處理正則表達式操作。以下是一些常見的正則表達式操作的代碼示例:

1. 簡單匹配(MatchString)

用于檢查字符串是否匹配某個正則表達式。

package main

import (
	"fmt"
	"regexp"
)

func main() {
	pattern := `^hello`
	text := "hello world"

	match, _ := regexp.MatchString(pattern, text)
	fmt.Println("Matched:", match) // 輸出: Matched: true
}

2. 編譯正則表達式(Compile 和 MustCompile)

通過 regexp.Compile 或 regexp.MustCompile 編譯正則表達式以提高性能。

package main

import (
	"fmt"
	"regexp"
)

func main() {
	// Compile 返回 error,如果正則無效
	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 會 panic,如果正則無效
	re2 := regexp.MustCompile(`\d+`)
	fmt.Println("Matched:", re2.MatchString(text)) // 輸出: Matched: true
}

3. 查找字符串中的第一個匹配項(FindString 和 FindStringSubmatch)

  • FindString 返回第一個匹配的字符串。
  • FindStringSubmatch 返回第一個匹配的字符串以及捕獲的子組。
package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile(`(\d+)-(\d+)-(\d+)`)
	text := "Today's date is 2025-01-25."

	// 找到第一個匹配的字符串
	match := re.FindString(text)
	fmt.Println("Found:", match) // 輸出: Found: 2025-01-25

	// 找到第一個匹配及其子組
	submatches := re.FindStringSubmatch(text)
	fmt.Println("Submatches:", submatches) // 輸出: Submatches: [2025-01-25 2025 01 25]
}

4. 查找所有匹配項(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)

通過一個函數(shù)動態(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)

使用正則表達式分割字符串。

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)

通過命名捕獲組提取特定的子組。

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 檢查整個字符串。
  • 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包常見的正則表達式操作的文章就介紹到這了,更多相關(guān)Go regexp正則表達式操作內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家! 

相關(guān)文章

  • Golang+Vue輕松構(gòu)建Web應(yīng)用的方法步驟

    Golang+Vue輕松構(gòu)建Web應(yīng)用的方法步驟

    本文主要介紹了Golang+Vue輕松構(gòu)建Web應(yīng)用,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-05-05
  • 最新評論