简体   繁体   English

查找 Go 中两个字符串之间的所有字符串

[英]Find all strings in between two strings in Go

I am working on extracting mutliple matches between two strings.我正在努力提取两个字符串之间的多重匹配。

In the example below, I am trying to regex out an AB C substring out of my string.在下面的示例中,我试图从我的字符串中正则表达式输出AB C substring。

Here is my code:这是我的代码:

package main
    
import (
    "fmt"
    "regexp"
)
    
func main() {
    str:= "Movies: A B C Food: 1 2 3"
    re := regexp.MustCompile(`[Movies:][^Food:]*`)
    match := re.FindAllString(str, -1)
    fmt.Println(match)
}

I am clearly doing something wrong in my regex.我显然在我的正则表达式中做错了什么。 I am trying to get the AB C string between Movies: and Food: .我正在尝试在Movies:Food:之间获取AB C字符串。

What is the proper regex to get all strings between two strings?获取两个字符串之间的所有字符串的正确正则表达式是什么?

In Go, since its RE2-based regexp does not support lookarounds, you need to use capturing mechanism with regexp.FindAllStringSubmatch function:在 Go 中,由于其基于 RE2 的正则regexp不支持环视,您需要使用regexp.FindAllStringSubmatch function 的捕获机制:

left := "LEFT_DELIMITER_TEXT_HERE"
right := "RIGHT_DELIMITER_TEXT_HERE"
rx := regexp.MustCompile(`(?s)` + regexp.QuoteMeta(left) + `(.*?)` + regexp.QuoteMeta(right))
matches := rx.FindAllStringSubmatch(str, -1)

Note the use of regexp.QuoteMeta that automatically escapes all special regex metacharacters in the left- and right-hand delimiters.请注意使用regexp.QuoteMeta自动转义左右分隔符中的所有特殊正则表达式元字符。

The (?s) makes . (?s)使. match across lines and (.*?) captures all between ABC and XYZ into Group 1.跨行匹配和(.*?)ABCXYZ之间的所有内容捕获到第 1 组中。

So, here you can use所以,在这里你可以使用

package main

import (
    "fmt"
    "regexp"
)

func main() {
    str:= "Movies: A B C Food: 1 2 3"
    r := regexp.MustCompile(`Movies:\s*(.*?)\s*Food`)
    matches := r.FindAllStringSubmatch(str, -1)
        for _, v := range matches {
            fmt.Println(v[1])
        }   
}

See the Go demo .请参阅Go 演示 Output: AB C . Output: AB C

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM