Golang

关注公众号 jb51net

关闭
首页 > 脚本专栏 > Golang > Go regexp正则表达式操作

Go中regexp包常见的正则表达式操作

作者:学亮编程手记

本文主要介绍了Go中regexp包常见的正则表达式操作,包括匹配、查找、替换和分割字符串等,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

在 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)

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)

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]

	// 限制返回的匹配数量
	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."

	// 替换所有匹配的数字为 XXX
	result := re.ReplaceAllString(text, "XXX")
	fmt.Println("Replaced:", result) // 输出: Replaced: Order XXX, XXX, and XXX.
}

6. 替换字符串(ReplaceAllStringFunc)

通过一个函数动态替换匹配的字符串。

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)

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. 替换字节切片(ReplaceAll)

与字符串操作类似,但作用于字节切片。

package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile(`\d+`)
	text := []byte("Order 123, 456, and 789.")

	// 替换所有匹配的数字为 XXX
	result := re.ReplaceAll(text, []byte("XXX"))
	fmt.Println("Replaced:", string(result)) // 输出: Replaced: Order XXX, XXX, and XXX.
}

到此这篇关于Go中regexp包常见的正则表达式操作的文章就介绍到这了,更多相关Go regexp正则表达式操作内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

您可能感兴趣的文章:
阅读全文