【问题标题】:Unicode Substitutions using Regex , Python使用正则表达式的 Unicode 替换,Python
【发布时间】:2014-11-05 08:54:17
【问题描述】:

我有一个字符串如下:

str1 = "heylisten\uff08there is something\uff09to say \uffa9"

我需要将正则表达式检测到的 unicode 值替换为两边的空格。

所需的输出字符串:

out = "heylisten \uff08 there is something \uff09 to say  \uffa9 "

我使用 re.findall 来获取所有匹配项,然后替换它们。它看起来像:

p1 = re.findall(r'\uff[0-9a-e][0-9]', str1, flags = re.U)  
out = str1
for item in p1:
    print item
    print out
    out= re.sub(item, r" " + item + r" ", out) 

这个输出:

'heylisten\\ uff08 there is something\\ uff09 to say \\ uffa9 ' 

上面打印了一个额外的“\”并将其与uff分开,这有什么问题?我什至尝试使用re.search,但它似乎只将\uff08 分开。有没有更好的办法?

【问题讨论】:

  • 但是您似乎没有更换任何东西? !!
  • 我没听懂你。我希望每场比赛的两边都有空格。但 \ 似乎分开了。

标签: python regex unicode


【解决方案1】:

我有一个字符串如下:

str1 = "heylisten\uff08there is something\uff09to say \uffa9"

我需要替换 unicode 值...

您没有任何 unicode 值。你有一个字节串。

str1 = u"heylisten\uff08there is something\uff09to say \uffa9"
 ...
p1 = re.sub(ur'([\uff00-\uffe9])', r' \1 ', str1)

【讨论】:

  • 它不起作用.. 输出 'heylisten\\uff08there is something\\uff09to say \\uffa9'
  • 是的,我读过它,我想我把这个例子框错了..它适用于外面的你..
【解决方案2】:
print re.sub(r"(\\uff[0-9a-e][0-9])", r" \1 ", x)

您可以直接使用这个re.sub。见演示。

http://regex101.com/r/sU3fA2/67

import re
p = re.compile(ur'(\\uff[0-9a-e][0-9])', re.UNICODE)
test_str = u"heylisten\uff08there is something\uff09to say \uffa9"
subst = u" \1 "

result = re.sub(p, subst, test_str)

输出:

heylisten \uff08 there is something \uff09 to say  \uffa9

【讨论】:

  • 您的导入代码输出如下:u'heylisten\uff08there is something\uff09to say \uffa9'
  • @Swordy 直接使用print re.sub(r"(\\uff[0-9a-e][0-9])", r" \1 ", x) x 是你的字符串。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 2011-04-29
  • 2012-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多