I have a string and I want to match something at the start and end with a single search pattern. How can this be done?
Let’s say we have a string like:
string = "ftp://www.somewhere.com/over/the/rainbow/image.jpg"
I want to do something like this:
re.search("^ftp:// & .jpg$" ,string)
Obviously, it’s incorrect, but I hope it gets my point across. Is this possible?
re.matchwill match the string at the beginning, in contrast tore.search:Two things to note here:
r''is used for the string literal to make it trivial to have backslashes inside the regexstringis a standard module, so I chosesas a variabler = re.compile(...)to built the state machine once and then user.match(s)afterwards to match the stringsIf you want, you can also use the
urlparsemodule to parse the URL for you (though you still need to extract the extension):