I am looking for an approach to the following problem. It captures all *
values from the string using a provided pattern.
function capture(pattern, string) {
}
Example:
Input
Pattern The quick brown * jumps over the lazy *
String The quick brown fox jumps over the lazy dog
Output [fox, dog]
Is it possible to solve it using regex?
The trick is to convert the pattern into a regular expression that captures the expected values from the given string:
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
", capture(pat, str))
// OK: [fox dog]
}
In 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)