In the Django urls I need an optional named group. This conf without arguments raised an 404 exception:
r'^list_cv/(?P<category>[\d]+)?/$'
How to make optional named group?
The question mark is called a quantifier. You can make several tokens optional by grouping them together using parentheses, and placing the question mark after the closing parenthesis.
Python has a module named re to work with RegEx. Here's an example: import re pattern = '^a...s$' test_string = 'abyss' result = re. match(pattern, test_string) if result: print("Search successful.") else: print("Search unsuccessful.")
Adding ? after the non-capturing group makes the whole non-capturing group optional. Alternatively, you could do: \".
The re.This method returns a tuple containing all the subgroups of the match, from 1 up to however many groups are in the pattern. The default argument is used for groups that did not participate in the match; it defaults to None. In later versions (from 1.5. 1 on), a singleton tuple is returned in such cases.
Works this way to me:
r'^list_cv/(?:(?P<category>[\w+])/)?$'
Comparing to the original answer the difference is in the repetition match.
(?:(?P<category>[\w+])/)?$
vs original (?:(?P<category>[\w+])?/)$
.
The last slash should be part of the optional RE, and the RE should be like
r'^list_cv/(?:(?P<category>[\w+])?/)$'
I didn't test it, though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With