为了账号安全,请及时绑定邮箱和手机立即绑定

匹配 begging 和 end 字符而不从另一个搜索中获取它们

匹配 begging 和 end 字符而不从另一个搜索中获取它们

Go
呼唤远方 2022-06-13 15:26:44
如果不使用正则表达式环顾四周(go 不支持),我如何匹配开始和结束字符而不从另一个搜索中获取它们。例如:想要匹配任何具有空格、逗号或分号以及开头和结尾的“狗”或“猫”。所以:“狗狗,猫猫;”将匹配“狗”,“狗”,“猫”。到目前为止,我所拥有的 (?:[ ,;]|^)(cat|dog)(?:[ ,;]|$) 将返回 "dog" "cat" 因为在匹配之间使用空格
查看完整描述

1 回答

?
慕无忌1623718

TA贡献1744条经验 获得超4个赞

我真的只看到用 Go 做这件事的几种方法。


最直接的方法是只匹配一侧,然后做一些后正则表达式逻辑:


https://play.golang.org/p/1_4fi-4kMhi


content := []byte("dog dog, cat cats; ")

re := regexp.MustCompile(`(?:[ ,;]|^)(cat|dog)`)

matches := re.FindAllIndex(content, -1)

for _, match := range matches {

    next := string(content[match[1]])

    if next == "," || next == " " || next == ";" {

        fmt.Println(string(content[match[0]:match[1]+1]))

    }

}

另一种方法是复制任何分隔符:


https://play.golang.org/p/krDlmHfepA1


content := []byte("dog dog, cat cats; ")

re := regexp.MustCompile(`([ ,;])`)

content = re.ReplaceAll(content, []byte("$1$1"))

fmt.Println(string(content))

re = regexp.MustCompile(`(?:[ ,;]|^)(cat|dog)(?:[ ,;]|$)`)

matches := re.FindAllSubmatch(content, -1)

for _, match := range matches {

    for _, submatch := range match[1:] {

        fmt.Println(string(submatch))    

    }

}


查看完整回答
反对 回复 2022-06-13
  • 1 回答
  • 0 关注
  • 159 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号