正则匹配指定字符串 2023-04-22

2023-04-21  本文已影响0人  夏树的宝马
package main

import (
    "fmt"
    "log"
    "regexp"
)

func TestZ_1() {
    str := "Hello ${world}, this is ${golang}"
    re := regexp.MustCompile(`\${(.+?)\}`)

    // 查到匹配的字符串下标
    matches_index := re.FindAllStringIndex(str, -1)
    log.Println(matches_index)

    //查到匹配的字符串
    log.Println(re.FindAllString(str, -1))

    //查到匹配的字符串以及子字符串
    log.Println(re.FindAllStringSubmatch(str, -1))

    //把匹配到的字符串替换成指定的串
    log.Println(re.ReplaceAllString(str, "%s"))

    str_replace := re.ReplaceAllString(str, "%s")

    mathc_all := re.FindAllStringSubmatch(str, -1)
    // 参数准备并替换尝试
    math_list := make([]interface{}, 0)
    for _, match := range mathc_all {
        math_list = append(math_list, match[1])
    }

    log.Println(math_list, len(math_list))
    for i := 0; i < len(math_list); i++ {
        log.Println("匹配到", math_list[i])
    }
    log.Println("待替换的字符串 ", str_replace)
    log.Println("替换后的数据", fmt.Sprintf(str_replace, math_list...))
}

func main() {
    TestZ_1()
}


执行结果
2023/04/22 21:13:00 [[6 14] [24 33]]
2023/04/22 21:13:00 [${world} ${golang}]
2023/04/22 21:13:00 [[${world} world] [${golang} golang]]
2023/04/22 21:13:00 Hello %s, this is %s
2023/04/22 21:13:00 [world golang] 2
2023/04/22 21:13:00 匹配到 world
2023/04/22 21:13:00 匹配到 golang
2023/04/22 21:13:00 待替换的字符串  Hello %s, this is %s
2023/04/22 21:13:00 替换后的数据 Hello world, this is golang

参考:https://cloud.tencent.com/developer/article/1706173

上一篇下一篇

猜你喜欢

热点阅读