go 正则表达式

这篇具有很好参考价值的文章主要介绍了go 正则表达式。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1. go 正则表达式

A regular expression is a useful feature in a programming language to check whether or not the string contains the desired value. It can not only check but also extract the data from the string.

In this post, we’ll go through the basic usage of regexp.

1.1. Check if the string contains the desired value

Let’s start with an easy example. The first one only checks if the value is contained in a string. regexp must be imported to use regular expression, which will be written as regex in the following.

import (
    "fmt"
    "regexp"
)

func runMatch() {
    reg, err := regexp.Compile("ID_\\d")
    if err != nil {
        fmt.Println("error in regex string")
    }

    fmt.Println(reg.Match([]byte("ID_1")))   // true
    fmt.Println(reg.Match([]byte("ID_ONE"))) // false

    fmt.Println(reg.MatchString("ID_1"))   // true
    fmt.Println(reg.MatchString("ID_123")) // true
    fmt.Println(reg.MatchString("something_ID_123")) // true
    fmt.Println(reg.MatchString("ID_ONE")) // false
}

We have to compile the regex string first by regexp.Compile(“string here”). It returns a regex instance which can actually be used to do something with the regex string.

The example search for ID_<number>. \d is a metacharacter that has a special meaning. It is the same as [0-9] which means one-digit number. If it is [2-9], it expects numbers in the range of 2 to 9.

A backslash is handled as an escape character. The next character is handled as a metacharacter. If the metacharacter isn’t defined, Compile method returns an error.

regexp.Compile("ID_\\d") used in the example has two backslashes because the second one must be handled as a normal character. We can use back quotes instead.

regexp.Compile(`ID_\d`)

It handles the string as a raw string. A backslash is handled as a normal character.

The Match method accepts only a byte array but it also provides a string version.

fmt.Println(reg.Match([]byte("ID_1")))   // true
fmt.Println(reg.Match([]byte("ID_ONE"))) // false

fmt.Println(reg.MatchString("ID_1"))   // true
fmt.Println(reg.MatchString("ID_ONE")) // false

Use the right one depending on the data type.

1.2. MustCompile should not be used

There is MustCompile method. It can be used to get an instance of regex but it panics if the regex string is invalid.

func panicCompile() {
    defer func() {
        if r := recover(); r != nil {
            // panic:  regexp: Compile(`ID_\p`): error parsing regexp: invalid character class range: `\p`
            fmt.Println("panic: ", r)
        }
    }()

    regexp.MustCompile("ID_\\p")
}

\p is not a defined meta character and thus it’s invalid. Generally, MustCompile should not be used because it panics. It’s much better to use the normal Compile method and handle the error result correctly.

Don’t use MustCompile without any good reason!

1.3. Make the regex string always valid by QuoteMeta

QuoteMeta should be used if the regex string needs to be generated depending on input. Note that metacharacters can’t be used in this case because it escapes the special characters.

func useQuoteMeta() {
    originalStr := "ID_\\p"
    quotedStr := regexp.QuoteMeta(originalStr)
    fmt.Println(originalStr) // ID_\p
    fmt.Println(quotedStr)   // ID_\\p
    _, err := regexp.Compile(quotedStr)
    if err != nil {
        fmt.Println("error in regex string")
    }
}

The original string is invalid as we saw in the previous section but it becomes a valid string by QuoteMeta(). It escapes all special characters.

1.4. Find the desired word in a string by FindAllString

FindString or FindAllString can be used to find the specified word in a string. The string is not a fixed word when regex is necessary. So metacharacters should be used in this case. In the following case, it finds all matches with ID_X.

func runFindSomething() {
    reg, _ := regexp.Compile(`ID_\d`)

    text := "ID_1, ID_42, RAW_ID_52, "
    fmt.Printf("%q\n", reg.FindAllString(text, 2))  // ["ID_1" "ID_4"]
    fmt.Printf("%q\n", reg.FindAllString(text, 5))  // ["ID_1" "ID_4" "ID_5"]
    fmt.Printf("%q\n", reg.FindString(text))        // "ID_1"
}

Set the desired value to the second parameter if you want to limit the number of results. If the value is bigger than the number of the matched string, the result contains all the results. The behavior is the same as FindString if it’s set to 1.

Set -1 if all the matched string needs to be used.

result := reg.FindAllString(text, -1)
fmt.Printf("%q\n", result)    // ["ID_1" "ID_4" "ID_5"]
fmt.Printf("%q\n", result[2]) // "ID_5"

Use Index method if the index is needed to cut the string for example.

fmt.Printf("%v\n", reg.FindAllStringIndex(text, 5)) // [[0 4] [6 10] [17 21]]

1.5. Extract the desired word/value from a string by Submatch

How can we implement it if we want to know the key and the value? If the string is ID_1, the key is ID and value is 1. Submatch method needs to be used in this case but the following way doesn’t work well.

text := "ID_1, ID_42, RAW_ID_52, "
reg, _ := regexp.Compile(`ID_\d`)
fmt.Printf("%q\n", reg.FindAllStringSubmatch(text, -1)) // [["ID_1"] ["ID_4"] ["ID_5"]]

The last key must be RAW_ID and the matched strings need to be split by an underbar _. It’s not a good way. The target values can be extracted by using parenthesis (). To get the key-value, it can be written in the following way. There are some metacharacters. If you are not familiar with the syntax, go to the official site.

reg2, err := regexp.Compile(`([^,\s]+)_(\d+)`)
if err != nil {
    fmt.Println("error in regex string")
}

fmt.Printf("%q\n", reg2.FindAllString(text, -1)) // ["ID_1" "ID_42" "RAW_ID_52"]
result2 := reg2.FindAllStringSubmatch(text, -1)
fmt.Printf("%q\n", result2) // [["ID_1" "ID" "1"] ["ID_42" "ID" "42"] ["RAW_ID_52" "RAW_ID" "52"]]
fmt.Printf("Key: %s, ID: %s\n", result2[2][1], result2[2][2])

FindAllString just returns the matched string but we need additional work for it to get the key-value. Submatch method returns a nice value. The first index is always the whole matched string that appears in FindAllString. The second index corresponds to the first parenthesis. It’s key in this case. Then, the third one corresponds to the value. With this result, we can easily use the key-value in the following code.文章来源地址https://www.toymoban.com/news/detail-674507.html

到了这里,关于go 正则表达式的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • MySQL正则表达式 | 事务详解

    目录 一、正则表达式 实例操作 二、事务 事务控制语句 MYSQL 事务处理主要有两种方法 SQL测试代码 PHP中使用事务实例 使用保留点 SAVEPOINT MySQL可以通过  LIKE ...%  来进行模糊匹配。 MySQL 同样也支持其他正则表达式的匹配, MySQL中使用 REGEXP 操作符来进行正则表达式匹配。 如果

    2023年04月18日
    浏览(28)
  • MySQL正则表达式检索数据

    目录 一、使用正则表达式进行基本字符匹配 1.使用regexp 2.使用正则表达式  .  二、进行OR匹配 1.为搜索两个串之一,使用   |   2.匹配几个字符之一[] 3.匹配范围  4.匹配特殊字符 过滤数据允许使用 匹配、比较、通配符 操作来寻找数据,但是随着过滤条件的复杂性增

    2024年02月14日
    浏览(29)
  • mysql 正则表达式 提取 指定字符

    eg: 使用正则表达式来进行匹配替换: REGEXP_REPLACE(\\\'需要进行替换的字段‘, ‘被替换的’,‘替换的内容’) eg: 模式 说明 ^ 匹配输入字符串的开始位置。如果设置了 RegExp 对象的 Multiline 属性,^ 也匹配 ‘n’ 或 ‘r’ 之后的位置。 $ 匹配输入字符串的结束位置。

    2024年02月06日
    浏览(36)
  • MySQL数据库——MySQL REGEXP:正则表达式

    正则表达式主要用来查询和替换符合某个模式(规则)的文本内容。例如,从一个文件中提取电话号码,查找一篇文章中重复的单词、替换文章中的敏感语汇等,这些地方都可以使用正则表达式。正则表达式强大且灵活,常用于非常复杂的查询。 MySQL 中,使用  REGEXP  

    2024年02月01日
    浏览(38)
  • 【MySQL】不允许你不会用正则表达式进行搜索

    🎬 博客主页:博主链接 🎥 本文由 M malloc 原创,首发于 CSDN🙉 🎄 学习专栏推荐:LeetCode刷题集! 🏅 欢迎点赞 👍 收藏 ⭐留言 📝 如有错误敬请指正! 📆 未来很长,值得我们全力奔赴更美好的生活✨ 😁大家好呀,今天是我第N次写MySQL,也是最近才学习MySQL,也想着记录

    2024年02月11日
    浏览(44)
  • 【正则表达式】正则表达式常见匹配模式

    模式 描述 w 匹配字母数字及下划线 W 匹配非字母数字下划线 s 匹配任意空白字符,等价于 [tnrf]. S 匹配任意非空字符 d 匹配任意数字,等价于 [0-9] D 匹配任意非数字 A 匹配字符串开始 Z 匹配字符串结束,如果是存在换行,只匹配到换行前的结束字符串 z 匹配字符串结

    2024年02月09日
    浏览(65)
  • 【SQL-正则】利用正则表达式进行过滤操作(常用正则表达式)

    1、由数字、26个英文字母或者下划线组成的字符串 2、非负整数(正整数 + 0 ) 3、正整数 4、非正整数(负整数 + 0) 5、负整数 6、整数 7、非负浮点数(正浮点数 + 0) 8、正浮点数 9、非正浮点数(负浮点数 + 0) 10、负浮点数 11、浮点数 12、由26个英文字母组成的字符串 13、

    2024年02月12日
    浏览(66)
  • Java 之正则表达式语法及常用正则表达式汇总

    正则表达式,又称规则表达式。(英语:Regular Expression,在代码中常简写为 regex、regexp 或 RE),计算机科学的一个概念。正则表达式通常被用来检索、替换那些符合某个模式(规则)的文本。 正则表达式是对字符串(包括普通字符(例如,a 到 z 之间的字母)和特殊字符(称

    2024年02月09日
    浏览(57)
  • Python正则表达式之学习正则表达式三步曲

            正则表达式描述了一种字符串匹配的模式,可以用来检查一个串的有无某子串,或者做子串匹配替换,取出子串等操作。也可以说正则表达式就是字符串的匹配规则,也可以理解为是一种模糊匹配,匹配满足正则条件的字符串。         1、数据验证(eg:表单验

    2024年02月15日
    浏览(49)
  • 老夫的正则表达式大成了,桀桀桀桀!!!【Python 正则表达式笔记】

    特殊字符 .^$?+*{}[]()| 为特殊字符,若想要使用字面值,必须使用 进行转义 字符类 [] [] 匹配包含在方括号中的任何字符。它也可以指定范围,例: [a-zA-Z0-9] 表示a到z,A到Z,0到9之间的任何一个字符 [u4e00-u9fa5] 匹配 Unicode 中文 [^x00-xff] 匹配双字节字符(包括中文) 在 [] 中

    2024年02月04日
    浏览(47)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包