Dollar sign ($) at the end of URL patterns in Torn

2019-07-31 02:19发布

I've seen some URLs regexps ending with a $ in a Tornado app that was handed to my team... Maybe I'm not the most web literate guy and this is obvious for others, but I don't see the difference it makes to explicitly indicate the end of line when matching the whole string (not searching inside).

Is there something that I'm missing or it is just redundant?

edit to make clearer what I mean:

   handlers = [
        tornado.web.URLSpec(r'/About/$', ShowSettingsHandler),
        ...
   ]

that should be exactly the same as:

   handlers = [
        tornado.web.URLSpec(r'/About/', ShowSettingsHandler),
        ...
   ]

as the handler dispatcher looks for an exact match, not a substring.

2条回答
家丑人穷心不美
2楼-- · 2019-07-31 02:59

There is no need for the trailing $ in Tornado. I put them in out of habit, and because I think it's clearer, but r"^/hello" will ONLY match /hello.

We can see this by looking at the URLSpec source:

if not pattern.endswith('$'):
    pattern += '$'
查看更多
聊天终结者
3楼-- · 2019-07-31 03:05

The difference is that the $ sign ensures that the pattern even if matched fully, is not a substring of another pattern. See these two regexes to match url patterns.

  1. with $ sign : http://regexr.com?327d2

  2. without $ sign : http://regexr.com?327d5

And here is some excerpt from the djangobook, which may be relevant to tornado as well :

^hello/$

The pattern includes a caret (^) and a dollar sign ($). These are regular expression characters that have a special meaning: the caret means “require that the pattern matches the start of the string,” and the dollar sign means “require that the pattern matches the end of the string.”

This concept is best explained by example. If we had instead used the pattern '^hello/' (without a dollar sign at the end), then any URL starting with /hello/ would match, such as /hello/foo and /hello/bar, not just /hello/. Similarly, if we had left off the initial caret character (i.e., 'hello/$'), Django would match any URL that ends with hello/, such as /foo/bar/hello/. If we had simply used hello/, without a caret or dollar sign, then any URL containing hello/ would match, such as /foo/hello/bar. Thus, we use both the caret and dollar sign to ensure that only the URL /hello/ matches — nothing more, nothing less.

查看更多
登录 后发表回答