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

 更新时间:2025年02月21日 10:10:12   作者:学亮编程手记  
本文主要介绍了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)

  • 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]

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

  • 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正则表达式操作内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

相关文章

  • 基于Golang实现统一加载资源的入口

    基于Golang实现统一加载资源的入口

    当我们需要在 main 函数中做一些初始化的工作,比如初始化日志,初始化配置文件,都需要统一初始化入口函数,所以本文就来编写一个统一加载资源的入口吧
    2023-05-05
  • Golang标准库之errors包应用方式

    Golang标准库之errors包应用方式

    Go语言的errors包提供了基础的错误处理能力,允许通过errors.New创建自定义error对象,error在Go中是一个接口,通过实现Error方法来定义错误文本,对错误的比较通常基于对象地址,而非文本内容,因此即使两个错误文本相同
    2024-10-10
  • go实现冒泡排序的示例代码

    go实现冒泡排序的示例代码

    这篇文章主要介绍了go实现冒泡排序的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-01-01
  • Go语言中实现完美错误处理实践分享

    Go语言中实现完美错误处理实践分享

    Go 语言是一门非常流行的编程语言,由于其高效的并发编程和出色的网络编程能力,越来越受到广大开发者的青睐。本文我们就来深入探讨一下Go 语言中的错误处理机制吧
    2023-04-04
  • Go语言RPC Authorization进行简单ip安全验证的方法

    Go语言RPC Authorization进行简单ip安全验证的方法

    这篇文章主要介绍了Go语言RPC Authorization进行简单ip安全验证的方法,实例分析了Go语言进行ip验证的技巧,需要的朋友可以参考下
    2015-03-03
  • golang遍历处理map时的常见性能陷阱与解决方法

    golang遍历处理map时的常见性能陷阱与解决方法

    这篇文章主要为大家详细介绍了Golang中有关循环处理map时的性能优化,本文主要介绍了常见的三种场景,文中的示例代码讲解详细,需要的可以了解下
    2025-05-05
  • golang基础之Interface接口的使用

    golang基础之Interface接口的使用

    这篇文章主要介绍了golang基础之Interface接口的使用,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-07-07
  • golang 通过ssh代理连接mysql的操作

    golang 通过ssh代理连接mysql的操作

    这篇文章主要介绍了golang 通过ssh代理连接mysql的操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-12-12
  • Go语言LeetCode题解682棒球比赛

    Go语言LeetCode题解682棒球比赛

    这篇文章主要为大家介绍了Go语言LeetCode题解682棒球比赛示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-12-12
  • Go语言中双Token登录系统的思路与实现详解

    Go语言中双Token登录系统的思路与实现详解

    在现代Web应用中,身份认证是保障系统安全的重要环节,本文将介绍如何使用Go语言实现双Token登录系统,文中的示例代码讲解详细,需要的可以了解下
    2025-07-07

最新评论