1

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?

2 Answers 2

1

I guess the easiest is to make the first capturing group optional in the first regex:

(.* )?(son)\s+(is)\s+(21) .*

See demo

Sign up to request clarification or add additional context in comments.

Comments

0

Just put ^, .* inside a group delimited by pipe symbol at the start.

r1 = re.compile(r"(?:^|.* )(son)\s+(is)\s+(21) .*")

2 Comments

Wouldn't the additional spaces in there cause issues? (?:^|.*)(son)\s+(is)\s+(21).*")
@Leb yep. without the space , fooson is 21 will got a match.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.