python - Django slug, `\w` 未检测到韩语 + 中文

标签 python regex django

我有一个 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 可以很好地同时处理两种语言。

最佳答案

来自python documentation :

\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/

相关文章:

python - celery 教程 : NotRegistered error

执行 .split() 后返回字典的 python 列表理解

iphone - 用于剥离 HTML 标记的 NSRegularExpression

python - 模板 password_reset_form.html 不会覆盖 django 管理模板

python - IPython支持python版本3.2.3吗?如果没有,为什么?

Python:即使引用的文件存在也找不到文件

python - 支持旧的和新的 URI 版本都可以在不破坏 reverse() 的情况下工作

正则表达式用逗号替换所有换行符

使用验证 V2 Golang 包的正则表达式电话号码不起作用

django - 如何通过 nginx 提供 django 媒体文件?