Reputation: 1323
To capture both of the following expressions:
str1 = "my son is 21 now"
str2 = "son is 21 now"
These two re statements and filters each capture one respectively:
r1 = re.compile(".* (son)\s+(is)\s+(21) .*")
r2 = re.compile("(son)\s+(is)\s+(21) .*")
m1 = filter(r1.match, [str1, str2])
m2 = filter(r2.match, [str1, str2])
How would I combine r1
and r2
into one re statement such that both strings will be matched?
Upvotes: 1
Views: 65
Reputation: 627082
I guess the easiest is to make the first capturing group optional in the first regex:
(.* )?(son)\s+(is)\s+(21) .*
See demo
Upvotes: 1
Reputation: 174776
Just put ^
, .*
inside a group delimited by pipe symbol at the start.
r1 = re.compile(r"(?:^|.* )(son)\s+(is)\s+(21) .*")
Upvotes: 0