登录
首页 >  Golang >  Go问答

如何在特定数量的字符后查找正则表达式模式

来源:stackoverflow

时间:2024-03-30 08:21:29 255浏览 收藏

在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《如何在特定数量的字符后查找正则表达式模式》,聊聊,希望可以帮助到正在努力赚钱的你。

问题内容

我需要在 go 程序中搜索 n 字符之后的正则表达式模式。 这是我到目前为止所尝试过的。我有一个字符串,我正在尝试匹配 n = 3 个字符后的模式。我需要通过正则表达式模式本身来实现这一点,而不是切片字符串。

package main

import (
    "fmt"
    "regexp"
)

func main() {
    str := "abcdefgh"
    rx := regexp.MustCompile(`\A[^.{3}]d`)
    matched := rx.FindString(str)
    fmt.Println(matched)

    // expecting output as `d`
    // In regex, `\A` should start the regex check at the start of the string
    // In regex, `[^.{3}]` should mean that match any 3 characters at start and then skip them
    // in regex, `d` should mean that match only d
    // but I am not getting d. Something is not working as expected
}

正确答案


我不确定您习惯使用哪种正则表达式语法,但这在 go 中不起作用。您应该使用的正则表达式是:

regexp.mustcompile(`^.{3}(d)`)

这将通知 go 匹配第四个字符是“d”的任何字符串,并且它应该专门匹配“d”。

接下来,您不想使用 findstring,因为它将返回与正则表达式匹配的字符串片段,在本例中为“abcd”。相反,您应该使用 findstringsubmatch,它将在出现匹配组时返回它们。由于您正在寻找第一个子组,因此您需要第一个匹配组:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    str := "abcdefgh"
    rx := regexp.MustCompile(`^.{3}(d)`)
    matched := rx.FindStringSubmatch(str)[1]
    fmt.Println(matched)
}

今天关于《如何在特定数量的字符后查找正则表达式模式》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>