• 设为首页
  • 收藏本站
  • 积分充值
  • VIP赞助
  • 手机版
  • 微博
  • 微信
    微信公众号 添加方式:
    1:搜索微信号(888888
    2:扫描左侧二维码
  • 快捷导航
    福建二哥 门户 查看主题

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

    发布者: 竹韵9933 | 发布时间: 2025-8-14 05:35| 查看数: 116| 评论数: 0|帖子模式

    在 Golang 中,
    1. regexp
    复制代码
    包用于处理正则表达式操作。以下是一些常见的正则表达式操作的代码示例:

    1. 简单匹配(MatchString)

    用于检查字符串是否匹配某个正则表达式。
    1. package main

    2. import (
    3.         "fmt"
    4.         "regexp"
    5. )

    6. func main() {
    7.         pattern := `^hello`
    8.         text := "hello world"

    9.         match, _ := regexp.MatchString(pattern, text)
    10.         fmt.Println("Matched:", match) // 输出: Matched: true
    11. }
    复制代码
    2. 编译正则表达式(Compile 和 MustCompile)

    通过
    1. regexp.Compile
    复制代码
    1. regexp.MustCompile
    复制代码
    编译正则表达式以提高性能。
    1. package main

    2. import (
    3.         "fmt"
    4.         "regexp"
    5. )

    6. func main() {
    7.         // Compile 返回 error,如果正则无效
    8.         re, err := regexp.Compile(`\d+`)
    9.         if err != nil {
    10.                 fmt.Println("Error compiling regex:", err)
    11.                 return
    12.         }

    13.         text := "Order number 12345"
    14.         fmt.Println("Matched:", re.MatchString(text)) // 输出: Matched: true

    15.         // MustCompile 会 panic,如果正则无效
    16.         re2 := regexp.MustCompile(`\d+`)
    17.         fmt.Println("Matched:", re2.MatchString(text)) // 输出: Matched: true
    18. }
    复制代码
    3. 查找字符串中的第一个匹配项(FindString 和 FindStringSubmatch)


      1. FindString
      复制代码
      返回第一个匹配的字符串。
      1. FindStringSubmatch
      复制代码
      返回第一个匹配的字符串以及捕获的子组。
    1. package main

    2. import (
    3.         "fmt"
    4.         "regexp"
    5. )

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

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

    12.         // 找到第一个匹配及其子组
    13.         submatches := re.FindStringSubmatch(text)
    14.         fmt.Println("Submatches:", submatches) // 输出: Submatches: [2025-01-25 2025 01 25]
    15. }
    复制代码
    4. 查找所有匹配项(FindAllString 和 FindAllStringSubmatch)


      1. FindAllString
      复制代码
      返回所有匹配的字符串。
      1. FindAllStringSubmatch
      复制代码
      返回所有匹配的字符串及其子组。
    1. package main

    2. import (
    3.         "fmt"
    4.         "regexp"
    5. )

    6. func main() {
    7.         re := regexp.MustCompile(`\d+`)
    8.         text := "Numbers: 123, 456, and 789."

    9.         // 找到所有匹配的字符串
    10.         matches := re.FindAllString(text, -1)
    11.         fmt.Println("Matches:", matches) // 输出: Matches: [123 456 789]

    12.         // 限制返回的匹配数量
    13.         limitedMatches := re.FindAllString(text, 2)
    14.         fmt.Println("Limited Matches:", limitedMatches) // 输出: Limited Matches: [123 456]
    15. }
    复制代码
    5. 替换字符串(ReplaceAllString)

    用于替换所有匹配的字符串。
    1. package main

    2. import (
    3.         "fmt"
    4.         "regexp"
    5. )

    6. func main() {
    7.         re := regexp.MustCompile(`\d+`)
    8.         text := "Order 123, 456, and 789."

    9.         // 替换所有匹配的数字为 XXX
    10.         result := re.ReplaceAllString(text, "XXX")
    11.         fmt.Println("Replaced:", result) // 输出: Replaced: Order XXX, XXX, and XXX.
    12. }
    复制代码
    6. 替换字符串(ReplaceAllStringFunc)

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

    2. import (
    3.         "fmt"
    4.         "regexp"
    5.         "strings"
    6. )

    7. func main() {
    8.         re := regexp.MustCompile(`[a-z]+`)
    9.         text := "hello world GO!"

    10.         // 将匹配的字符串替换为大写
    11.         result := re.ReplaceAllStringFunc(text, strings.ToUpper)
    12.         fmt.Println("Replaced:", result) // 输出: Replaced: HELLO WORLD GO!
    13. }
    复制代码
    7. 分割字符串(Split)

    使用正则表达式分割字符串。
    1. package main

    2. import (
    3.         "fmt"
    4.         "regexp"
    5. )

    6. func main() {
    7.         re := regexp.MustCompile(`\s+`) // 匹配空白字符
    8.         text := "Split   this     string!"

    9.         // 分割字符串
    10.         parts := re.Split(text, -1)
    11.         fmt.Println("Parts:", parts) // 输出: Parts: [Split this string!]
    12. }
    复制代码
    8. 提取子组并命名(Named Captures)

    通过命名捕获组提取特定的子组。
    1. package main

    2. import (
    3.         "fmt"
    4.         "regexp"
    5. )

    6. func main() {
    7.         re := regexp.MustCompile(`(?P<Year>\d{4})-(?P<Month>\d{2})-(?P<Day>\d{2})`)
    8.         text := "Date: 2025-01-25."

    9.         // 提取所有子组
    10.         submatches := re.FindStringSubmatch(text)
    11.         fmt.Println("Submatches:", submatches) // 输出: Submatches: [2025-01-25 2025 01 25]

    12.         // 提取命名的子组
    13.         names := re.SubexpNames()
    14.         for i, name := range names {
    15.                 if name != "" {
    16.                         fmt.Printf("%s: %s\n", name, submatches[i])
    17.                 }
    18.         }
    19.         // 输出:
    20.         // Year: 2025
    21.         // Month: 01
    22.         // Day: 25
    23. }
    复制代码
    9. 检查字符串起始位置匹配(MatchString 和 Match)


      1. MatchString
      复制代码
      检查整个字符串。
      1. Match
      复制代码
      检查字节切片。
    1. package main

    2. import (
    3.         "fmt"
    4.         "regexp"
    5. )

    6. func main() {
    7.         re := regexp.MustCompile(`^hello`)

    8.         text := "hello world"
    9.         bytes := []byte("hello bytes")

    10.         fmt.Println("String Match:", re.MatchString(text)) // 输出: String Match: true
    11.         fmt.Println("Bytes Match:", re.Match(bytes))      // 输出: Bytes Match: true
    12. }
    复制代码
    10. 替换字节切片(ReplaceAll)

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

    2. import (
    3.         "fmt"
    4.         "regexp"
    5. )

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

    9.         // 替换所有匹配的数字为 XXX
    10.         result := re.ReplaceAll(text, []byte("XXX"))
    11.         fmt.Println("Replaced:", string(result)) // 输出: Replaced: Order XXX, XXX, and XXX.
    12. }
    复制代码
    到此这篇关于Go中regexp包常见的正则表达式操作的文章就介绍到这了,更多相关Go regexp正则表达式操作内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    来源:互联网
    免责声明:如果侵犯了您的权益,请联系站长(1277306191@qq.com),我们会及时删除侵权内容,谢谢合作!

    最新评论

    QQ Archiver 手机版 小黑屋 福建二哥 ( 闽ICP备2022004717号|闽公网安备35052402000345号 )

    Powered by Discuz! X3.5 © 2001-2023

    快速回复 返回顶部 返回列表