This question already has an answer here:
How do I extract values from a string based on a pattern?
This is the pattern I have: Member-[A-Za-z]+-Age%d+
Examples: Member-John-Age50
, Member-Peter-Age120
I would like to extract both the name
and the age
given a string that matches the pattern.
</div>
-[A-Za-z]+-
for the names and \d+
for the ages. For example:
import "regexp"
import "fmt"
func main() {
r, _ := regexp.Compile(`Member-([A-Za-z]+)-Age(\d+)`) // Pay attention, no ", instead `
name, _ := regexp.Compile(`-[A-Za-z]+-`)
age, _ := regexp.Compile(`\d+`)
matched_strings := r.FindAllString("oMember-John-Age50, jvienvujfeuvfejvwMember-Peter-Age120jvfjemvfjenvfeuvnuru", -1)
for i := range matched_strings {
name := name.FindString(matched_strings[i])
name = name[1:len(name)-1]
age := age.FindString(matched_strings[i])
fmt.Println(name, age) // John 50, Peter 120
}
}
Now this is me trying to continue to use regex, of course you could do it other ways. The name and age should be stored in the variables and you can use them however you want.