Instead of regex, use urlparse+urlunparse