在Python中使用正则表达式从列表中删除元素

13
我试图在Python中从列表中删除括号内的字符串,但没有成功。请看以下代码:
full = ['webb', 'ellis', '(sportswear)']
regex = re.compile(r'\b\(.*\)\b')
filtered = [i for i in full if not regex.search(i)]

返回:

['webb', 'ellis', '(sportswear)']

有人能指出我的错误吗?


从模式中删除\b。那么,您想要删除所有包含(...)的项目吗?还是只有完全在括号内的项目? - Wiktor Stribiżew
那些在括号内的内容。不包括括号。 - Istvan
啊哈,所以你需要使用 match()r'\(.*\)$' - Wiktor Stribiżew
3个回答

12
\b 单词边界不允许在字符串开头匹配 (,因为没有单词存在(即在模式中,\b 要求在 ( 之前必须有字母、数字或下划线,但这种情况并不满足)。
如果要匹配完全被 (...) 包括的值,则需要使用 regex = re.compile(r'\(.*\)$')re.match
使用:
import re
full = ['webb', 'ellis', '(sportswear)']
regex = re.compile(r'\(.*\)$')
filtered = [i for i in full if not regex.match(i)]
print(filtered)

查看IDEONE演示

re.match将匹配定位在字符串的开头,$将匹配定位在字符串的结尾。

请注意,如果您的字符串中有换行符,请在编译正则表达式时使用flags=re.DOTALL(以便.也可以匹配换行符)。


另外,由于有re.matchre.searchre.fullmatch,因此您可以使用re.compile(r'^\(.*\)$')(与re.search一起使用)和re.compile(r'\(.*\)')(与re.fullmatch一起使用)。 - Wiktor Stribiżew

3
>>> import re
>>> full = ['webb', 'ellis', '(sportswear)']
>>> x = filter(None, [re.sub(r".*\(.*\).*", r"", i) for i in full])
>>> x
['webb', 'ellis']

3
对于我的使用场景,这很有效。 也许对于遇到同样问题的人会有帮助。
doc_list = dir(obj)
regex = re.compile(r'^__\w*__$')
filtered = [ele for ele in doc_list if not regex.match(ele)]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接