在 Golang 中,包用于处理正则表达式操作。以下是一些常见的正则表达式操作的代码示例:
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)
通过或编译正则表达式以提高性能。- 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正则表达式操作内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
来源:互联网
免责声明:如果侵犯了您的权益,请联系站长(1277306191@qq.com),我们会及时删除侵权内容,谢谢合作! |
|