Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional named groups Python re

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?

like image 506
I159 Avatar asked Nov 25 '11 14:11

I159


People also ask

How do I make a group optional in RegEx in Python?

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.

How do you use re in Python?

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.")

How do you make a string optional in RegEx?

Adding ? after the non-capturing group makes the whole non-capturing group optional. Alternatively, you could do: \".

WHAT IS group in Python re?

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.


2 Answers

Works this way to me:

r'^list_cv/(?:(?P<category>[\w+])/)?$'

EDIT:

Comparing to the original answer the difference is in the repetition match.

(?:(?P<category>[\w+])/)?$ vs original (?:(?P<category>[\w+])?/)$.

like image 170
I159 Avatar answered Sep 23 '22 17:09

I159


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.

like image 38
Mohammad Tayseer Avatar answered Sep 19 '22 17:09

Mohammad Tayseer