Python regex match in groups -
i'm trying put following string 2 groups follows:
groups(1) = "hello1 hello2 hello3 hello4" groups(2) = "bye1 bye2 bye3 bye4" i tried using following code. however, boths groups not contain desired words.
import re string = "hello1 hello2 hello3 hello4 bye1 bye2 bye3 bye4" pattern = r'(hello[0-9])+\w(bye[0-9])+' result = re.search(pattern, string) groups = result.group print("group 1: {}\ngroup 2: {}".format(groups(1), groups(2)))
this seems doing job, although being different approach used in initial post.
import re string = "hello1 hello2 hello3 hello4 bye1 bye2 bye3 bye4" patterns = [r'hello[0-9]', r'bye[0-9]'] results = [re.findall(patterns[idx], string) idx in range(len(patterns))] print("results:", results)
Comments
Post a Comment