如何使用正则表达式指定长URL模式以遵循PEP8指南
我在Django中有一个很长的URL模式,类似于这个:
url(r'^(?i)top-dir/(?P<first_slug>[-\w]+?)/(?P<second_slug>[-\w]+?)/(?P<third_slug>[-\w]+?).html/$',
'apps.Discussion.views.pricing',
这显然不符合PEP8的规范,因为一行中的字符超过了80个。我找到了解决这个问题的两种方法:
第一种方法(使用反斜杠):
url(r'^(?i)top-dir/(?P<first_slug>[-\w]+?)/(?P<second_slug>[-\w]+?)'\
'/(?P<third_slug>[-\w]+?).html/$',
'apps.Discussion.views.pricing',
第二种方法 - 使用括号:
url((r'^(?i)top-dir/(?P<first_slug>[-\w]+?)/(?P<second_slug>[-\w]+?)',
r'/(?P<third_slug>[-\w]+?).html/$'),
'apps.Discussion.views.pricing'),
这两种方法在正则表达式中都会出问题。有没有更好的方法来解决这个问题?或者说,写这么长的正则表达式处理URL是不是一种不好的做法?
2 个回答
-2
PEP8没有关于正则表达式格式化的建议。不过你可以试试以下这些方法:
- 使用 re.compile,这样可以获得以下好处:
- 匹配或搜索时更快
- 可以用一个(简短的)名字来引用它们!
- 把正则表达式写成多行,并留空格
- 使用 re.VERBOSE 来忽略正则表达式字符串中的空白
- 使用标志而不是“魔法组”(比如
(?i) → re.IGNORECASE
)
slugs = re.compile(r'''
^
top-dir/
(?P<first_slug>[-\w]+?)/
(?P<second_slug>[-\w]+?)/
(?P<third_slug>[-\w]+?).html/
$
''', re.VERBOSE|re.IGNORECASE)
url(slugs, 'apps.Discussion.views.pricing', ...)
29
相邻的字符串会被连接在一起,所以你可以这样做:
url(r'^(?i)top-dir/(?P<first_slug>[-\w]+?)/'
r'(?P<second_slug>[-\w]+?)/'
r'(?P<third_slug>[-\w]+?).html/$',
'apps.Discussion.views.pricing',)