根据模式[关闭]从字符串中捕获值

问题描述 投票:-6回答:2

我正在寻找解决以下问题的方法。它使用提供的模式从字符串中捕获所有*值。

function capture(pattern, string) {
}

例:

输入

  • 模式The quick brown * jumps over the lazy *
  • 字符串The quick brown fox jumps over the lazy dog

输出[fox, dog]

是否可以使用正则表达式来解决它?

javascript python regex go
2个回答
2
投票

诀窍是将模式转换为正则表达式,捕获给定字符串中的预期值:

func capture(pat, str string) []string {
    // Capture all sequences of non-whitespace characters between word boundaries.
    re := strings.Replace(pat, "*", `(\b\S+\b)`, -1)
    groups := regexp.MustCompile(re).FindAllStringSubmatch(str, -1)
    if groups == nil {
        return []string{}
    }
    return groups[0][1:]
}

func main() {
    pat := "The quick brown * jumps over the lazy *"
    str := "The quick brown fox jumps over the lazy dog"

    fmt.Printf("OK: %s\n", capture(pat, str))
    // OK: [fox dog]
}

0
投票

在python中:

str = "The quick brown fox jumps over the lazy dog"
pat = "The quick brown * jumps over the lazy *"

result = []
for p, s in zip(pat.split(), str.split()):
    if p == "*":
        result.append(s)

print(result)
© www.soinside.com 2019 - 2024. All rights reserved.