Q:

How to do if-else in regex based on previous regex in the pattern (Python)?

I'm trying to match urls of the form
r'https://.*\.mysite.com'
However, one will notice that if there is no subdomain .mysite.com isn't going to be valid. If there is a subdomain such as sub.mysite.com, only then do I want a dot in front of mysite, otherwise, I want 0 dots (or more generally, characters) between https:// and mysite.com
How do I accomplish this?

A:

This doesn't seem to be a Python-specific problem but more of a RegEx one.
You could modify your expression to optionally accept a subdomain as such:
https:\/\/([^.]+\.)?mysite\.com

Or allow for multi-level subdomains:
https:\/\/([^.]+\.)*mysite\.com

Additionally, if you didn't want to use a capture group, you could use a non-capturing group:
https:\/\/(?:[^.]+\.)*mysite\.com

