登录
首页 >  Golang >  Go问答

Golang 复杂正则表达式与 FindAllStringSubmatch

来源:stackoverflow

时间:2024-04-21 11:30:34 363浏览 收藏

珍惜时间,勤奋学习!今天给大家带来《Golang 复杂正则表达式与 FindAllStringSubmatch》,正文内容主要涉及到等等,如果你正在学习Golang,或者是对Golang有疑问,欢迎大家关注我!后面我会持续更新相关内容的,希望都能帮到正在学习的大家!

问题内容

我有一个超级英雄字符串,他们所有人都有名字,但是并非所有人都有属性。

它的格式为 ⛦name⛯attrname☾attrdata☽,其中 attrname☾attrdata☽ 是可选的。

因此,superheroes 字符串是:

⛦超人⛯衬衫☾蓝色☽⛦小丑⛯⛦蜘蛛侠⛯年龄☾15yo☽girlfriend☾cindy☽

我想使用正则表达式提取字符串,并将结果填充到地图切片中,如下所示:

[ {name: superman, shirt: blue},
  {name: joker},
  {name: spiderman, age: 15yo, girlfriend: cindy} ]

我无法在 go 演示中完成它。我使用正则表达式 ⛦(\\w+)⛯(?:(\\w+)☾(\\w+)☽)*,但它只能捕获单个属性,即正则表达式无法捕获 age 属性。 p>

我的代码是:

func main() {
    re := regexp.mustcompile("⛦(\\w+)⛯(?:(\\w+)☾(\\w+)☽)*")
    fmt.printf("%q\n", re.findallstringsubmatch("⛦superman⛯shirt☾blue☽⛦joker⛯⛦spiderman⛯age☾15yo☽girlfriend☾cindy☽", -1))
}

go 演示代码在这里:https://play.golang.org/p/epv66lvwurk

运行结果为:

[
    ["⛦superman⛯shirt☾blue☽" "superman" "shirt" "blue"]
    ["⛦joker⛯" "joker" "" ""]
    ["⛦spiderman⛯age☾15yo☽girlFriend☾Cindy☽" "spiderman" "girlFriend" "Cindy"]
]

age 丢失了,知道吗?


解决方案


您无法使用单个捕获组捕获任意数量的子字符串。您需要首先匹配整个记录,然后将其子部分与另一个正则表达式匹配。

查看示例:

package main

import (
    "fmt"
    "regexp"
)

func main() {

    str := "⛦superman⛯shirt☾blue☽⛦joker⛯⛦spiderman⛯age☾15yo☽girlfriend☾cindy☽"

    re_main := regexp.mustcompile(`⛦(\w+)⛯((?:\w+☾\w+☽)*)`)
    re_aux := regexp.mustcompile(`(\w+)☾(\w+)☽`)
    for _, match := range re_main.findallstringsubmatch(str, -1) {
        fmt.printf("%v\n", match[1])
        for _, match_aux := range re_aux.findallstringsubmatch(match[2], -1) {      
            fmt.printf("%v: %v\n", match_aux[1], match_aux[2])
        }
        fmt.println("--end of match--") 
    }  
}

参见Go demo

输出:

superman
shirt: blue
--end of match--
joker
--end of match--
spiderman
age: 15yo
girlfriend: cindy
--end of match--

这里,⛦(\w+)⛯((?:\w+☾\w+☽)*) 是主正则表达式,它匹配并捕获第 1 组主“键”和另一个键的字符串 -值被捕获到第 2 组中。然后,您需要迭代找到的匹配项,并使用 (\w+)☾(\w+)☽ 从第 2 组收集所有键值。

您已将您的 regex 设置为 ⛦(\\w+)⛯(?:(\\w+)☾(\\w+)☽)*,它仅打印两个级别的 keyvalue,就像它根据您的 regex 打印一样:

[["⛦superman⛯shirt☾blue☽" "superman" "shirt" "blue"]
["⛦joker⛯" "joker" "" ""]
["⛦spiderman⛯age☾15yo☽girl☾cindy☽" "spiderman" "girl" "cindy"]]

我将正则表达式再增加一对 keyvalue 对,它也会打印 age 值,请按照以下 regex 代码进行操作:

re := regexp.MustCompile("⛦(\\w+)⛯(?:(\\w+)☾(\\w+)☽)*(?:(\\w+)☾(\\w+)☽)*")
    fmt.Printf("%q\n", re.FindAllStringSubmatch("⛦superman⛯shirt☾blue☽⛦joker⛯⛦spiderman⛯age☾15yo☽girl☾Cindy☽", -1))

今天关于《Golang 复杂正则表达式与 FindAllStringSubmatch》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

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