Search code examples
pythonregextornado

what is the difference between (.*js$) and .*(js)$


I'm using tornado to build a server. It is based on python and I need to do as below:

application.add_handlers(r"^(www).*",[
    (r"/(.*js$)", tornado.web.StaticFileHandler, {'path': 'static/'}),
    (r"/(.*xml$)", tornado.web.StaticFileHandler, {'path': 'static/'}),
    (r"/(.*css$)", tornado.web.StaticFileHandler, {'path': 'static/'}),
    (r"/(.*jpg$)", tornado.web.StaticFileHandler, {'path': 'static/'}),
    (r"/(.*png$)", tornado.web.StaticFileHandler, {'path': 'static/'}),
    (r"/(.*ico$)", tornado.web.StaticFileHandler, {'path': 'static/'}),
    (r"/(.*html$)", tornado.web.StaticFileHandler, {'path': 'static/'}),

    (r"/$", IndexHandler),
])

The code above is about to tell a http request the location of resource that it requests. So here I tell a http request that it can get js, xml, css, jpg, png, ico and html files under the path ./static/.

It does work well but I don't quite understand the regex part.
As you see r"/(.*js$)" is a regex, which is to match a http request. If the http request is looking for a js file, the first regex will be matched but I dont' know how.

As my understanding, if I want to match a js file, I need to make a regex like this: r"/.*(js)$", which means that the files ending with js. I tried but it doesn't work.

So why does (.*js$) work? Doesn't it mean that files ending with one letter s instead of js? What is the difference between .*(js)$ and (.*js$)? Moreover, what id the difference between ^.*abc$, .*abc$, ^.*abc, .*(abc)$, ^.*(abc)?

I must misunderstand or can't understand some rules about (), ^ and $ in regex.


Solution

  • 'why does (.*js$) work?`

    Above regex match anything that ends with js and not only file with extension js
    See this regex demo with explanation.

    To match a file that has the js extension you need the following regex

    (.*\.js$)