sanic-org / sanic-guide

Frontpage and user guide for Sanic

Home Page:https://sanic.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add documentation on partial segment matching

ahopkins opened this issue · comments

Sometimes you want to match on a part of a path segment:

/image/123456789.jpg

If you wanted to match the file pattern, but only capture the numeric portion, you need to do some regex fun:

app.route("/image/<img_id:(?P<img_id>\d+)\.jpg>")

This should be documented in the routing section.

OK, but I have a question
which part is suitable? I think we can add it as an tip under the
routing -> Supported types -> regex

image

what do you think? @ahopkins @ZinkLu

commented

I tried group () and named group (?P<>), both works. so the idea is use regex group to get partial url? may be we should point that and have a python regex link below.

ie. https://docs.python.org/3/library/re.html?highlight=re%20compile#regular-expression-syntax

That seems like a reasonable place to put it.

These should all be acceptable:

@app.get(r"/<foo:[a-z]{3}.txt>")
@app.get(r"/<foo:([a-z]{3}).txt>")
@app.get(r"/<foo:(?P<foo>[a-z]{3}).txt>")
@app.get(r"/<foo:(?P<foo>[a-z]{3}).(?:txt)>")
  1. matching on the full pattern
  2. defining a single matching group
  3. defining a single named matching group
  4. defining a single named matching group, with one or more non-matching groups

Also, if using a named matching group, it must be the same as the segment label.

Got it, I will do that in this weekend.