how to write such a regular expression in Python
Question: I want to write a python regular expression which match a URL like the
following rules.

  1. start with "http://"
  2. in the domain part, end with "some.domain"
  3. in the path part, exclude end with a list of words like "tar", "zip"
  4. the url may contain optional query part, like "?key1=value1&key2=value2"

For example, "<http://some.domain/a.zip>",
"<http://sub.some.domain/a.zip?key=value>" matches this pattern,
"<http://www.other.domain/a.zip>", "<http://www.some.domain/a.zipp>" dose not
match.


Answer: As others have said in the comments, best to use a URL parser as URLs in
particular can vary wildly and you could miss. However, here's one example
that does what I believe you want.

    
    
    #!/usr/bin/python
    
    import re
    
    strings = [ 
                "http://some.domain/", 
                "http://some.domain/a.zip", 
                "http://some.domain/a.tar",
                "http://sub.some.domain/a.zip?key=value", 
                "http://www.other.domain/a.zip", 
                "http://www.some.domain/a.zipp0"
                ]
    
    for url in strings:
    
        # match "http://"
        # match anything up to "some.domain/", greedy
        # match "some.domain/"
        # optionally, match anything up to .zip or .tar, greedy
        # match ".tar" or ".zip", if above optional is present
        # optionally, match a "?" after .zip/.tar, followed by anything, greedy
        # match the end of string
    
        if re.search(r'http://.*some\.domain/(.*\.(zip|tar)(\?.*)?)?$', url):
            print("url: {} MATCHES".format(url))
        else:
            print("url: {} DOESN'T MATCH".format(url))
    

Output:

    
    
    ./url.py
    url: http://some.domain/ MATCHES
    url: http://some.domain/a.zip MATCHES
    url: http://some.domain/a.tar MATCHES
    url: http://sub.some.domain/a.zip?key=value MATCHES
    url: http://www.other.domain/a.zip DOESN'T MATCH
    url: http://www.some.domain/a.zipp0 DOESN'T MATCH
    

-stevieb

