Here is my oneliner solution (edited).
urlpath.partition("?")[0].strip("/").replace("/", ".")
As some others have mentions, the speed improvements are negligible here. Aside from using re.compile() to precompile your expressions, I would start looking else where.
import re
re1 = re.compile("(\?.*|\/[0-9a-f]{24})")
re2 = re.compile("\/[0-9\/]*")
re3 = re.compile("\;.*")
re4 = re.compile("\/")
re5 = re.compile("\.api")
def orig_regex(urlpath):
urlpath=re1.sub("",urlpath)
urlpath=re2.sub("/",urlpath)
urlpath=re3.sub("",urlpath)
urlpath=re4.sub(".",urlpath)
urlpath=re5.sub("api",urlpath)
return urlpath
myregex = re.compile(r"([^/]+)")
def my_regex(urlpath):
return ".".join( x.group() for x in myregex.finditer(urlpath.partition('?')[0]))
def test_nonregex(urlpath)
return urlpath.partition("?")[0].strip("/").replace("/", ".")
def test_func(func, iterations, *args, **kwargs):
for i in xrange(iterations):
func(*args, **kwargs)
if __name__ == "__main__":
import cProfile as profile
urlpath = u'/api/v4/path/apiCallTwo?host=wApp&trackId=1347158'
profile.run("test_func(orig_regex, 10000, urlpath)")
profile.run("test_func(my_regex, 10000, urlpath)")
profile.run("test_func(non_regex, 10000, urlpath)")
Results
Iterating orig_regex 10000 times
60003 function calls in 0.108 CPU seconds
....
Iterating my_regex 10000 times
130003 function calls in 0.087 CPU seconds
....
Iterating non_regex 10000 times
40003 function calls in 0.019 CPU seconds
Without doing re.compile on your 5 regex results in
running <function orig_regex at 0x100532050> 10000 times
210817 function calls (210794 primitive calls) in 0.208 CPU seconds
regex- works fast and great! you can download from here: pypi.python.org/pypi/regex