golang正则regexp包使用-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]

https://blog.csdn.net/qq_41629756/article/details/100516635

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

玄德公笔记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值