我正在寻找解决以下问题的方法。它使用提供的模式从字符串中捕获所有*
值。
function capture(pattern, string) {
}
示例:
输入
模式The quick brown * jumps over the lazy *
字符串The quick brown fox jumps over the lazy dog
输出[fox, dog]
是否可以使用正则表达式来解决它?
答案 0 :(得分: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]
}
答案 1 :(得分: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)