Skip to content Skip to sidebar Skip to footer

Python Url Matching (regex)

I've tried to match a the below URL for a couple of hours and can't seem to figure it out and Im quite sure its not that difficult: The URL can be this: /course/lesson-one/ or it

Solution 1:

You use ? if you need optional parts.

/course/([a-zA-Z][-a-zA-Z]*)/([a-zA-Z][-a-zA-Z]*/)?
#                                                 ^

(Note that [a-zA-Z]+[-a-zA-Z]* is equivalent to [a-zA-Z][-a-zA-Z]*.)

Use an additional grouping (?:…) to exclude the / from the match, while allowing multiple elements to be optional at once:

/course/([a-zA-Z][-a-zA-Z]*)/(?:([a-zA-Z][-a-zA-Z]*)/)?
#                            ~~~                     ~^

Your 2nd regex swallows the last character, because:

  /course/([a-zA-Z]+[-a-zA-Z]*)/*([a-zA-Z]+[-a-zA-Z]*)/
          ^^^^^^^^^^^^^^^^^^^^^  ~~~~~~~~~~~~~~~~~~~~~
        this matches 'computer'  and this matches the 's'.

The second group in this regex required to match some alphabets with length 1 or more due to the +, so the 's' must belong there.

Solution 2:

use a "?" after something to make it considered optional.

>>>r = r"/course/([a-zA-Z]+[-a-zA-Z]*)(/[A-Z[a-z]+[-a-zA-Z]*)?">>>s = "/course/lesson-one/chapter-one/">>>re.match(r, s).groups()
('lesson-one', '/chapter-one')
>>>s = "/course/computers/">>>re.match(r, s).groups()
('computers', None)

Solution 3:

You can use the following regex:

'/course/([a-zA-Z]+[-a-zA-Z]*)(/([a-zA-Z]+[-a-zA-Z]*)/)?'

This makes the second part optional and still matches each of the parts of the URL.

Note that the second part of the URL has two groups: one that matches /chapter-one/ and one that matches chapter-one

>>> re.match('/course/([a-zA-Z]+[-a-zA-Z]*)(/([a-zA-Z]+[-a-zA-Z]*)/)?', '/course/lesson-one/chapter-one/').groups()
('lesson-one', '/chapter-one/', 'chapter-one')

Similarly:

>>> re.match('/course/([a-zA-Z]+[-a-zA-Z]*)(/([a-zA-Z]+[-a-zA-Z]*)/)?', '/course/lesson-one/').groups()
('lesson-one', None, None)

Post a Comment for "Python Url Matching (regex)"