通过Python中的正则表达式从列表中删除元素

Ist*_*van 8 python regex

我试图从 Python 中的列表中删除括号中的字符串,但没有成功。

请参阅以下代码:

full = ['webb', 'ellis', '(sportswear)']
regex = re.compile(r'\b\(.*\)\b')
filtered = [i for i in full if not regex.search(i)]
Run Code Online (Sandbox Code Playgroud)

返回:

['webb', 'ellis', '(sportswear)']
Run Code Online (Sandbox Code Playgroud)

有人能指出我的错误吗?

Wik*_*żew 6

该\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)
Run Code Online (Sandbox Code Playgroud)

查看IDEONE 演示

在re.match将锚定匹配的字符串的开始,并且$将在字符串的结尾锚匹配。

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