[英]How to remove elements of a list containing specific patten with python?
Given a list of strings给定一个字符串列表
listA=['a', 'b', 'a@b=c', 'a @ b = c', 'a@ =b', 'a@=b' 'a=b@c', 'a@b' ]
^ ^
we want elements marked in "^" removed, and get我们希望删除标记在“^”中的元素,并得到
ListB=['a', 'b', 'a@ =b', 'a@=b' 'a=b@c', 'a@b']
Here we removed all elements containing '@', followed by some character, then followed by '=', but ignored "@=" or '@ ='这里我们删除了所有包含 '@' 的元素,后跟一些字符,然后是 '=',但忽略了“@=”或 '@='
How to do such regex matching for a python list?如何对 python 列表进行这样的正则表达式匹配?
EDIT:编辑:
I know if we know specific index of a elements to delete, we can use numpy.delete(list, index) to delete it.我知道如果我们知道要删除的元素的特定索引,我们可以使用 numpy.delete(list, index) 来删除它。 But it is not true in this case.
但在这种情况下并非如此。
Using the expression @\\s*\\S\\s*=
and re.search()
we can filter this list down:使用表达式
@\\s*\\S\\s*=
和re.search()
我们可以过滤这个列表:
import re
listB = [str for str in listA if re.search(r'@\s*\S\s*=', str) is None]
print listB
# ['a', 'b', 'a@ =b', 'a@=ba=b@c', 'a@b']
Regex searches in python can be done with the re
module; Python 中的正则表达式搜索可以通过
re
模块完成; specifically, re.search('@\\w=', my_string)
will not be None
if my_string
contains an @
and a =
separated by a member of \\w
, ie a word character (alphanumerics and _
).具体来说,
re.search('@\\w=', my_string)
如果my_string
包含一个@
和一个=
由\\w
的成员分隔,即一个单词字符(字母数字和_
) re.search('@\\w=', my_string)
则不会是None
。
I've expanded this to include cases where there's whitespace too, using \\s
.我已经使用
\\s
扩展了它以包括也有空格\\s
。
import re
listA = ['a', 'b', 'a@b=c', 'a @ b = c', 'a@ =b', 'a@=b' 'a=b@c', 'a@b' ]
listB = [a for a in listA if not re.search('@\s*\w+\s*=', a)]
Update: solution above now using \\w+
to match multiple word characters instead of just one.更新:上面的解决方案现在使用
\\w+
来匹配多个单词字符而不是一个。
import re
listA = ['a', 'b', 'a@b=c', 'a @ b = c', 'a@ =b', 'a@=b' 'a=b@c', 'a@b' ]
print [x for x in listA if not re.search(r'@\s*[a-zA-Z]\s*=', x)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.