Reputation: 17253
I am trying to understand the purpose of -
in this regex capture clause
(?P<slug>[\w-]+)
This is what I came up for when search for a dash
A dash (-) can be used to specify a range. So the dash is a metacharacter, but only within a character class.If you want to use a literal dash within a character class, you should escape it with a backslash, except when the dash is the first or last character of the character class. So, the regexp [a-z] is equal to [az-] and [-az], they will match any of those three characters.
My questions is what is the -
after \w
Upvotes: 0
Views: 141
Reputation: 522741
You are looking at what my former CS professor would refer to as a rabbit (out of a hat):
(?P<slug>[\w-]+)
The reason it is a rabbit is because normally your research is correct and dash is used as a part of a range of characters. But in this case, the dash is a literal dash, since it appears at the end of the character class.
So here [\w-]+
means to match one or more word characters or literal dashes.
If you want to include a literal dash in a character class, a safer way is to escape it:
[\w\-]+
Then, the dash may be placed anywhere in the class.
Upvotes: 1