06-其他用法

1. QuoteMeta() 函数(特殊字符转换)

将正则表达式的特殊字符转换。

语法

func QuoteMeta(s string) string

完整示例

package main
import (
"fmt"
"regexp"
)
func main() {
pattern := "玄德.*?"
myString := regexp.QuoteMeta(pattern)
fmt.Println(myString)
}
  • 结果
玄德\.\*\?

2. LiteralPrefix()方法(查找正则共同前缀)

语法

func (re *Regexp) LiteralPrefix() (prefix string, complete bool)

prefix:共同拥有的前缀
complete:如果 prefix 就是正则表达式本身,则返回 true,否则返回 false

完整示例

  • 代码
package main
import (
"fmt"
"regexp"
)
func main() {
reg := regexp.MustCompile(`Hello[\w\s]+`)
fmt.Println(reg.LiteralPrefix())
reg = regexp.MustCompile(`Hello`)
fmt.Println(reg.LiteralPrefix())
reg = regexp.MustCompile(`.*Hello`)
fmt.Println(reg.LiteralPrefix())
}
  • 结果
Hello false
Hello true
false

如上

  • 结果一,共同前缀hello被返回,false说明该前缀不是正则表达式字串本身
  • 结果二,共同前缀hello被返回,true说明该前缀是正则表达式字串本身
  • 结果三,没有共同前缀

3. Longest()方法(切换贪婪模式)

语法

func (re *Regexp) Longest()

完整示例

package main
import (
"fmt"
"regexp"
)
func main() {
s := `10.10.239.11`
reg := regexp.MustCompile(".*?\\.")
fmt.Printf("%s\n", reg.FindString(s))
reg.Longest() // 切换贪婪模式
fmt.Printf("%s\n", reg.FindString(s))
}
  • 结果
10.
10.10.239.

4. NumSubexp()方法(查询正则中分组个数)

语法

func (re *Regexp) NumSubexp() int

完整示例

  • 代码
package main
import (
"fmt"
"regexp"
)
func main() {
reg := regexp.MustCompile("(\\d+)\\.(\\d+)")
n := reg.NumSubexp()
fmt.Printf("正则中分组个数为:%d",n)
}
  • 结果
正则中分组个数为:2

5. Split() 方法(用正则切割)

语法

func (re *Regexp) Split(s string, n int) []string

完整示例

  • 代码
package main
import (
"fmt"
"regexp"
)
func main() {
reg := regexp.MustCompile(`\.`)
myString := "www.xishu.com"
result := reg.Split(myString, -1)
fmt.Printf("结果:%q\n",result )
}
  • 结果
结果:["www" "xishu" "com"]

6. String()方法 (将*regexp.Regexp实例中正则以string输出)

语法

func (re *Regexp) String() string

完整示例

package main
import (
"fmt"
"regexp"
)
func main() {
reg := regexp.MustCompile("\\d+$")
pattern := reg.String()
fmt.Printf("%s\n", pattern)
}
  • 结果
\d+$

7. SubexpNames() 方法(返回正则分组名)

语法

func (re *Regexp) SubexpNames() []string

给正则分组命名:

(?P<NAME>)

完整示例

package main
import (
"fmt"
"regexp"
)
func main() {
reg := regexp.MustCompile("(?P<first>\\d+)\\.(?P<second>\\d+)\\.(?P<third>\\d+)\\.(?P<fourth>\\d+)$")
namesList := reg.SubexpNames()
fmt.Printf("%+v\n", namesList)
}
  • 结果
[ first second third fourth]

posted on   运维开发玄德公  阅读(62)  评论(0编辑  收藏  举报  

相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示