在 Django 中使用 Python 正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1619554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Python Regular Expression in Django
提问by Noah Clark
I have an web address:
我有一个网址:
http://www.example.com/org/companyA
http://www.example.com/org/companyA
I want to be able to pass CompanyA to a view using regular expressions.
我希望能够使用正则表达式将 CompanyA 传递给视图。
This is what I have:
这就是我所拥有的:
(r'^org/?P<company_name>\w+/$',"orgman.views.orgman")
and it doesn't match.
它不匹配。
Ideally all URL's that look like example.com/org/X would pass x to the view.
理想情况下,所有看起来像 example.com/org/X 的 URL 都会将 x 传递给视图。
Thanks in advance!
提前致谢!
回答by Nicholas Riley
You need to wrap the group name in parentheses. The syntax for named groups is (?P<name>regex)
, not ?P<name>regex
. Also, if you don't want to require a trailing slash, you should make it optional.
您需要将组名括在括号中。命名组的语法是(?P<name>regex)
, not ?P<name>regex
。此外,如果您不想要求尾部斜杠,则应将其设为可选。
It's easy to test regular expression matching with the Python interpreter, for example:
使用 Python 解释器测试正则表达式匹配很容易,例如:
>>> import re
>>> re.match(r'^org/?P<company_name>\w+/$', 'org/companyA')
>>> re.match(r'^org/(?P<company_name>\w+)/?$', 'org/companyA')
<_sre.SRE_Match object at 0x10049c378>
>>> re.match(r'^org/(?P<company_name>\w+)/?$', 'org/companyA').groupdict()
{'company_name': 'companyA'}
回答by Alex Gaynor
Your regex isn't valid. It should probably look like
您的正则表达式无效。它应该看起来像
r'^org/(?P<company_name>\w+)/$'
回答by Oren S
It should look more like r'^org/(?P<company_name>\w+)'
它应该看起来更像 r'^org/(?P<company_name>\w+)'
>>> r = re.compile(r'^org/(?P<company_name>\w+)')
>>> r.match('org/companyA').groups()
('companyA',)