我有一个 url 的正则表达式:
r'^/review_metas/(?P<review_meta_id>\d+)/(?P<slug>[-~\w]+)/(?P<review_thread_id>\d+)/$'
以下网址确实匹配
/review_metas/2108/발견/24986/
以下网址不匹配,我想知道为什么?
/review_metas/2108/발견展/24986/
编辑
我其实有
url(r'^review/',
include('review.urls', namespace='review', app_name='review')),
review.urls 有
url(
r'^review_metas/(?P<review_meta_id>\d+)/(?P<slug>[-~\w]+)/(?P<review_thread_id>\d+)/$',
views.review.review_meta,
name='review_meta_thread'
),
为了尝试 Wiktor 的建议,我尝试添加 (?u)
^
之后在上述两个中的每一个中。但这会导致错误。
我尝试了imaluengo的建议
r'^/review_metas/(?P<review_meta_id>\d+)/(?P<slug>[^/]+)/(?P<review_thread_id>\d+)/$'
但它不起作用...
** 编辑 **
很抱歉给您带来了错误的电话,
这是由于客户端的 url 匹配(javascript 正则表达式)不起作用。
Django 可以很好地同时处理两种语言。
最佳答案
\w: When the LOCALE and UNICODE flags are not specified, matches any alphanumeric character and the underscore; this is equivalent to the set [a-zA-Z0-9_]. With LOCALE, it will match the set [0-9_] plus whatever characters are defined as alphanumeric for the current locale. If UNICODE is set, this will match the characters [0-9_] plus whatever is classified as alphanumeric in the Unicode character properties database.
您只需添加标志 re.UNICODE
让它工作并将字符串转换为 unicode(如 u'mystring'
或 unicode(string)
)。
>>> re.findall(r'\w+', '/review_metas/2108/발견/24986/')
['review_metas', '2108', '24986']
>>> re.findall(r'\w+', u'/review_metas/2108/발견/24986/', re.UNICODE)
[u'review_metas', u'2108', u'\ubc1c\uacac', u'24986']
<小时/>
在您的示例中:
>>> expr = r'^/review_metas/(?P<review_meta_id>\d+)/(?P<slug>[-~\w]+)/(?P<review_thread_id>\d+)/$'
>>> url = u'/review_metas/2108/발견/24986/'
>>> re.match(expr, url)
None
>>> f = re.match(expr, url, re.UNICODE)
>>> f
<_sre.SRE_Match at 0x7f2e08dd8620>
>>> f.group('slug')
u'\ubc1c\uacac'
只需传递正确的 unicode
字符串并添加 re.UNICODE
标志,您的解析器就可以正常工作。
我不知道 Django handle the URLS 怎么样?在内部(以前从未使用过 Django),但如果无法向 Django 提供 unicode 标志,则可以将 slug 模式 \w+
替换为 [ ^/]+
。
r'^/review_metas/(?P<review_meta_id>\d+)/(?P<slug>[^/]+)/(?P<review_thread_id>\d+)/$'
它读作除“/”之外的任何内容
。
关于python - Django slug, `\w` 未检测到韩语 + 中文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36514484/