【问题标题】:Match begging and end characters without taking them from another search匹配开始和结束字符而不从另一个搜索中获取它们
【发布时间】:2020-06-24 17:58:09
【问题描述】:

如果不使用正则表达式环顾四周(go 不支持),我如何匹配开始和结束字符而不从另一个搜索中获取它们。
例如:想要匹配任何包含空格、逗号或分号以及开头和结尾的“狗”或“猫”。

所以:“狗狗,猫猫;”将匹配“狗”,“狗”,“猫”。到目前为止,我所拥有的 (?:[ ,;]|^)(cat|dog)(?:[ ,;]|$) 将返回 "dog" "cat" 因为在匹配之间使用空格

【问题讨论】:

  • 只需更换两次。我在this answer 底部使用的相同技巧。

标签: regex go


【解决方案1】:

我真的只看到了几种使用 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))    
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 2018-02-28
    • 1970-01-01
    • 1970-01-01
    • 2014-09-15
    • 2020-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多