user1879926
user1879926

Reputation: 1323

Python re expression conditional match

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

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

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

Avinash Raj
Avinash Raj

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

Related Questions