• 设为首页
  • 收藏本站
  • 积分充值
  • VIP赞助
  • 手机版
  • 微博
  • 微信
    微信公众号 添加方式:
    1:搜索微信号(888888
    2:扫描左侧二维码
  • 快捷导航
    福建二哥 门户 查看主题

    Go正则表达式匹配字符串,替换字符串方式

    发布者: 嘉6148 | 发布时间: 2025-8-14 06:01| 查看数: 115| 评论数: 0|帖子模式

    Go正则表达式匹配字符串,替换字符串


    正则表达式
    1. package main

    2. import (
    3.     "fmt"
    4.     "regexp"
    5. )

    6. func main() {
    7.     match, err := regexp.MatchString("h[a-z]+.*d$", "hello world")
    8.     if err != nil {
    9.         panic(err)
    10.     }
    11.     fmt.Println(match)

    12.     match, err = regexp.MatchString("h[a-z]+.*d$", "ello world")
    13.     if err != nil {
    14.         panic(err)
    15.     }
    16.     fmt.Println(match)
    17. }

    18. // $ go run main.go
    19. // 输出如下
    20. /**
    21.   true
    22.   false
    23. */
    复制代码
    匹配所有子字符串
    1. package main

    2. import (
    3.     "fmt"
    4.     "regexp"
    5. )

    6. func main() {
    7.     c, err := regexp.Compile("h[a-z]")
    8.     if err != nil {
    9.         panic(err)
    10.     }

    11.     res := c.FindAllString("hello world", -1)
    12.     fmt.Printf("res = %v\n", res)

    13.     res2 := c.FindAllString("hello world hi ha h1", -1)
    14.     fmt.Printf("res2 = %v\n", res2)
    15. }

    16. // $ go run main.go
    17. // 输出如下
    18. /**
    19.   res = [he]
    20.   res2 = [he hi ha]
    21. */
    复制代码
    替换所有子字符串
    1. package main

    2. import (
    3.     "fmt"
    4.     "regexp"
    5. )

    6. func main() {
    7.     c, err := regexp.Compile("h[a-z]")
    8.     if err != nil {
    9.         panic(err)
    10.     }

    11.     res := c.ReplaceAll([]byte("hello world"), []byte("?"))
    12.     fmt.Printf("res = %s\n", res)

    13.     res2 := c.ReplaceAll([]byte("hello world hi ha h1"), []byte("?"))
    14.     fmt.Printf("res2 = %s\n", res2)
    15. }

    16. // $ go run main.go
    17. // 输出如下
    18. /**
    19.   res = ?llo world
    20.   res2 = ?llo world ? ? h1
    21. */
    复制代码
    匹配中文
    1. package main

    2. import (
    3.     "fmt"
    4.     "regexp"
    5. )

    6. func main() {
    7.     match, err := regexp.MatchString("\\x{4e00}-\\x{9fa5}", "hello world")
    8.     if err != nil {
    9.         panic(err)
    10.     }
    11.     fmt.Println(match)

    12.     match, err = regexp.MatchString("\\p{Han}+", "hello 世界")
    13.     if err != nil {
    14.         panic(err)
    15.     }
    16.     fmt.Println(match)
    17. }

    18. // $ go run main.go
    19. // 输出如下
    20. /**
    21.   false
    22.   true
    23. */
    复制代码
    总结

    以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

    来源:互联网
    免责声明:如果侵犯了您的权益,请联系站长(1277306191@qq.com),我们会及时删除侵权内容,谢谢合作!

    最新评论

    QQ Archiver 手机版 小黑屋 福建二哥 ( 闽ICP备2022004717号|闽公网安备35052402000345号 )

    Powered by Discuz! X3.5 © 2001-2023

    快速回复 返回顶部 返回列表