golang 正则匹配regexp接口实战学习

总览

如果不熟悉正则表达式的语法的话,可以执行下面命令:

go doc regexp/syntax

联系代码

package main

import (
    "fmt"
    "regexp"
)

func expandTest() {
    pat := `(((abc.)def.)ghi)`
    reg := regexp.MustCompile(pat)
    fmt.Println(reg.NumSubexp())

    src := []byte(`abc-def-ghi abc+def+ghi`)
    template := []byte(`$0   $1   $2   $3`)

    // 替换第一次匹配结果
    match := reg.FindSubmatchIndex(src)
    fmt.Printf("%v\n", match) // [0 11 0 11 0 8 0 4]
    dst := reg.Expand(nil, template, src, match)
    fmt.Printf("%s\n\n", dst)
    // abc-def-ghi   abc-def-ghi   abc-def-   abc-

    // 替换所有匹配结果
    for _, match := range reg.FindAllSubmatchIndex(src, -1) {
        fmt.Printf("%v\n", match)
        dst := reg.Expand(nil, template, src, match)
        fmt.Printf("%s\n", dst)
    }
    // [0 11 0 11 0 8 0 4]
    // abc-def-ghi   abc-def-ghi   abc-def-   abc-
    // [12 23 12 23 12 20 12 16]
    // abc+def+ghi   abc+def+ghi   abc+def+   abc+
}

func testFind() {
    re := regexp.MustCompile("a*r")
    fmt.Println(string(re.Find([]byte("paranoabrmal"))))
    fmt.Println(re.NumSubexp())

    rep := regexp.MustCompilePOSIX("a*r|ara")
    fmt.Println(string(rep.Find([]byte("paranoabrmal"))))
    fmt.Println(rep.NumSubexp())

    b := []byte("abc1def1")
    pat := `abc1|abc1def1`
    reg1 := regexp.MustCompile(pat)      // 第一匹配
    reg2 := regexp.MustCompilePOSIX(pat) // 最长匹配
    fmt.Printf("%s\n", reg1.Find(b))     // abc1
    fmt.Printf("%s\n", reg2.Find(b))     // abc1def1
    fmt.Println(reg1.NumSubexp())

    b = []byte("abc1def1"
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值