Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this Django regular expression mean? `?P`

I have the following regular expression (regex) in my urls.py and I'd like to know what it means. Specifically the (?P<category_slug> portion of the regex.

r'^category/(?P<category_slug>[-\w]+)/$ 
like image 447
locoboy Avatar asked Nov 03 '11 00:11

locoboy


People also ask

What does P mean in regex?

The P is Python identifier for a named capture group. You will see P in regex used in jdango and other python based regex implementations.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

What does P stand for in Python?

P stands for Placeholder . – kev. Apr 8, 2012 at 1:20.

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.


2 Answers

In django, named capturing groups are passed to your view as keyword arguments.

Unnamed capturing groups (just a parenthesis) are passed to your view as arguments.

The ?P is a named capturing group, as opposed to an unnamed capturing group.

http://docs.python.org/library/re.html

(?P<name>...) Similar to regular parentheses, but the substring matched by the group is accessible within the rest of the regular expression via the symbolic group name name. Group names must be valid Python identifiers, and each group name must be defined only once within a regular expression. A symbolic group is also a numbered group, just as if the group were not named. So the group named id in the example below can also be referenced as the numbered group 1.

like image 154
Yuji 'Tomita' Tomita Avatar answered Sep 30 '22 09:09

Yuji 'Tomita' Tomita


(?P<name>regex) - Round brackets group the regex between them. They capture the text matched by the regex inside them that can be referenced by the name between the sharp brackets. The name may consist of letters and digits.

Copy paste from: http://www.regular-expressions.info/refext.html

like image 30
Marcus Avatar answered Sep 30 '22 07:09

Marcus