3

urls.pyDjango

#urls.py
url(r'^topics/(?P<topic_id>\d+)/$', views.topic, name='topic')
The second part of the expression, /(?P<topic_id>\d+)/, matches an integer between two forward slashes and stores the integer value in an argument called topic_id.

我尝试用正则表达式来理解它

In [6]: re.findall(r'topics/(?P<topic_id>\d+)/$', "topics/1/")
Out[6]: ['1']

但是,当我尝试

In [7]: re.findall(r'topics/(?P<topic_id>\d+)/$', "topics/1/").topic_id
AttributeError: 'list' object has no attribute 'topic_id'

好像里面没有存储整数topic_id,怎么理解呢?

4

2 回答 2

5

您的错误不是来自“topic_id”,而是关于re.

如果您使用re.findall,它会返回与您的正则表达式匹配的所有列表。

所以在你的情况下,结果re.findall(r'topics/(?P<topic_id>\d+)/$', "topics/1/")将是['1']

所以,当然,['1'].topic_id引发 AttributeError。

如果您想分组'topic_id',请这样做

p = re.match(r'topics/(?P<topic_id>\d+)/$', "topics/1/")
p.group('topic_id') # it returns '1'
于 2018-05-10T14:48:29.113 回答
1

文档中:

re.findall(pattern, string, flags=0)以字符串列表的
形式返回字符串中所有不重叠的模式匹配。

您正在尝试从列表中检索该列表没有的属性。

于 2018-05-10T14:50:52.627 回答