Python 和带有 Unicode 的正则表达式 [英] Python and regular expression with Unicode

查看:85
本文介绍了Python 和带有 Unicode 的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从字符串 'بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ' 中删除一些 Unicode 符号

I need to delete some Unicode symbols from the string 'بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ'

我知道他们肯定存在在这里.我试过了:

I know they exist here for sure. I tried:

re.sub('([\u064B-\u0652\u06D4\u0670\u0674\u06D5-\u06ED]+)', '', 'بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ')

但它不起作用.字符串保持不变.我做错了什么?

but it doesn't work. String stays the same. What am I doing wrong?

推荐答案

您使用的是 python 2.x 还是 3.0?

Are you using python 2.x or 3.0?

如果您使用的是 2.x,请尝试使用 'u' 将正则表达式字符串设为 unicode 转义字符串.由于它是正则表达式,因此最好将正则表达式字符串设为带有 'r' 的原始字符串.此外,将整个模式放在括号中是多余的.

If you're using 2.x, try making the regex string a unicode-escape string, with 'u'. Since it's regex it's good practice to make your regex string a raw string, with 'r'. Also, putting your entire pattern in parentheses is superfluous.

re.sub(ur'[\u064B-\u0652\u06D4\u0670\u0674\u06D5-\u06ED]+', '', ...)

http://docs.python.org/tutorial/introduction.html#Unicode 字符串

对 unicode 正则表达式使用 re.UNICODE/re.U/(?u) 标志也是一个好习惯,但它只影响字符类别名,如 \w 或 \b,该模式不使用任何和所以不会受到影响.

It's also good practice to use the re.UNICODE/re.U/(?u) flag for unicode regexes, but it only affects character class aliases like \w or \b, of which this pattern does not use any and so would not be affected by.

这篇关于Python 和带有 Unicode 的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆