package main
import (
"fmt"
"regexp"
"regexp/syntax"
"strings"
)
func main() {
//regexpMain()
regexpSyntaxMain()
}
func regexpMain() {
// 解析正则表达式,如果成功,返回 一个可用于匹配文本的Regexp对象。
// 采用最左最短方式搜索
regexpCompile,err := regexp.Compile("foo.?")
if err != nil {
fmt.Println("regexpCompile err: ",err)
}
// 解析正则表达式,如果成功,返回 一个可用于匹配文本的Regexp对象。
// 采用最左最短方式搜索,如果表达式不能被解析就会panic
regexpMustCompile := regexp.MustCompile("foo(?P<first>.?)")
fmt.Println(regexpMustCompile.String())
// 解析正则表达式,如果成功,返回 一个可用于匹配文本的Regexp对象。
// 采用最左最长方式搜索
regexpCompilePOSIX,_ := regexp.CompilePOSIX("(foo.?)")
fmt.Println(regexpCompilePOSIX.String())
// 解析正则表达式,如果成功,返回 一个可用于匹配文本的Regexp对象。
// 采用最左最长方式搜索,如果表达式不能被解析就会panic
regexpMustCompilePOSIX := regexp.MustCompilePOSIX("foo.?")
fmt.Println(regexpMustCompilePOSIX.String())
// 返回用户匹配的正则源文本
regexpString := regexpCompile.String()
fmt.Println(regexpString)
// 从re复制的新的Regexp对象
regexpCopy := regexpCompile.Copy()
fmt.Println(regexpCopy.String())
// 统计正则表达式中的分组个数(不包括“非捕获的分组”)
regexpNumSubexp := regexpMustCompile.NumSubexp()
fmt.Println(regexpNumSubexp)
// 返回正则表达式中的分组名称列表,未命名的分组返回空字符串
regexpSubexpNames := regexpMustCompile.SubexpNames()
fmt.Println(regexpSubexpNames)
// 返回具有给定名称的第一个子表达式的索引,如果没有具有该名称的子表达式,则返回-1。
regexpSubexpIndex := regexpMustCompile.SubexpIndex("bob")
fmt.Println(regexpSubexpIndex)
// 返回以正则表达式任何开头的字符串,字符串包含整个正则则返回true
// 示例:foo.? 返回foo,true
regexpLiteralPrefixPrefix,regexpLiteralPrefixcomplete := regexpCompile.LiteralPrefix()
fmt.Println(regexpLiteralPrefixPrefix,regexpLiteralPrefixcomplete)
// 输入的数据 r(RuneReader) 是否包含正则表达式的任何匹配项
regexpMatchReader := regexpCompile.MatchReader(strings.NewReader("hello the food foo!"))
fmt.Println(regexpMatchReader)
// 输入的数据 r(String) 是否包含正则表达式的任何匹配项
regexpMatchString := regexpCompile.MatchString("hello the food foo!")
fmt.Println(regexpMatchString)
// 输入的数据 字节切片(Byte) 是否包含正则表达式的任何匹配项
go源码库学习之regexp库
最新推荐文章于 2025-10-13 22:47:39 发布
本文详细介绍Go语言中正则表达式的使用方法,包括不同方式的编译与匹配操作、字符串替换、查找等功能,并展示了如何利用正则表达式进行文本处理。

最低0.47元/天 解锁文章
268

被折叠的 条评论
为什么被折叠?



