Python正则表达式排除

2024-03-28 18:29:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在UNICODE中找到所有两个字符sumbols,除了下划线。当前溶质为:

pattern = re.compile(ur'(?:\s*)(\w{2})(?:\s*)', re.UNICODE | re.MULTILINE | re.DOTALL)
print pattern.findall('a b c ab cd vs sd a a_ _r')
['ab', 'cd', 'vs', 'sd', 'a_', '_r']

我需要从regex中排除下划线,因此找不到a_\u r。问题是,我的角色可以用任何语言。所以我不能像这样使用regex:[^a-zA-Z]。例如,俄语:

print pattern.findall(u'ф_')

Tags: reabunicodecdsd字符regexpattern
3条回答

排除任何非单词字符和

[^\W_]

而不是

\w

这似乎对我有用:

a="Exclude_from_search"
re.search("(\w[^_]+)", a).group(0)
'Exclude'

你最好用新的^{} module代替。它的一个特点是可以从字符集中删除个字符:

import regex as re

pattern = re.compile(ur'(?:\s*)([\w--_]{2})(?:\s*)', re.UNICODE | re.MULTILINE | re.DOTALL)

[\w--_]语法创建与\w相同的字符集,并从匹配字符中删除下划线字符。

相关问题 更多 >