删除子,如果不使用正则表达式
问题描述:
例如一个西班牙语单词,如果我有:删除子,如果不使用正则表达式
a = "aveces soñar es muy ließ y también человек"
我所要的输出是:
"aveces soñar es muy y también"
我使用正则表达式:“ [^ \ u0000- \u007FáéíóüñÁÉÓÓÜÑ¿¡] +'来匹配不属于西班牙语的字符,但是我不知道如何删除这个字,如果它包含其中一个字符。
有什么建议吗?
答
试试这个正则表达式(我相信通过您所提供的unicode的范围):
(?:^|\s)(?=\S*[^\u0000-\u007FáéíóúüñÁÉÍÓÚÜÑ¿¡])\S+
Substitute any match with a blank string. Click for Demo
说明:
-
(?:^|\s)
- 比赛无论是开始字符串或白色空间 -
(?=\S*[^\u0000-\u007FáéíóúüñÁÉÍÓÚÜÑ¿¡])
- positive lookahead以检查是否非西班牙字符存在或不存在 -
\S+
- 如果非西班牙字符的情况下(在步骤2中检查),匹配1+出现的非空白字符
Python代码(Generated):
# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"(?:^|\s)(?=\S*[^\u0000-\u007FáéíóúüñÁÉÍÓÚÜÑ¿¡])\S+"
test_str = "aveces soñar es muy ließ y también человек"
subst = ""
# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)
if result:
print (result)
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
你在用什么语言? –
我使用python 3.5.4 – looker