【发布时间】:2014-04-17 00:41:14
【问题描述】:
在第一个测试字符串中,我试图用空格替换文本中间的 Unicode 右箭头字符,但它似乎不起作用。
一般来说,我试图删除所有单个字符或多个 unicode “非单词”,但如果单词是 a-z0-9 和 unicode 的混合体或只是 \w
,则保留单词# -*- coding: utf-8 -*-
import re
str = 'hi… » Test'
str = 're of… » Pr'
str = 're of… » Pr | removepipeaswell'
print str
str = re.sub(r' [^a-z0-9]+ ', ' ', str , re.UNICODE|re.MULTILINE)
# str = re.sub(r' [^\p{Alpha}] ', ' ', str, re.UNICODE)
print str
're of… Pr removepipeaswell' #expected output
str_nbsp = 'afds » asf'
编辑:添加了另一个测试字符串,我不想删除“of...”(unicode 点),我只想删除多个 unicode(非单词)字符。
编辑:对测试用例使用它,(但不是在完整的 html 中??? - 它似乎只替换字符串前半部分的匹配项,然后忽略其余部分。)
str = re.sub(r' [^a-z0-9]+ ', ' ', str , re.UNICODE|re.MULTILINE)
编辑:fml,它必须是一些愚蠢的东西,比如没有正确阅读参数列表:http://bytes.com/topic/python/answers/689341-sub-does-not-replace-all-occurences
[刚刚删除回复的人 - 感谢您的帮助。]
str = re.sub(r' [^a-z0-9]+ ', ' ', str)
最终的测试字符串“str_nbsp”与上面的正则表达式不匹配。其中一个空格字符实际上是一个不间断的空格字符。我使用 www.regexr.com 并将鼠标悬停在每个字符上来解决这个问题。
【问题讨论】:
-
只是让您知道Stack Overflow Regular Expressions FAQ。 :)
-
谢谢。我是 perl 的正则表达式专家,但我是 python 的新手。仍然习惯于不同的语法。
-
Debuggex.com,如果你还不知道的话,它是一个同时使用 Python 和 PCRE 的在线测试器。
-
谢谢,我还发现 regexr.com 和 rubular.com 对于检查正则表达式也很有用。