![](/img/trans.png)
[英]Check list of strings and then match with the specific string to delete it from the list of strings
[英]Python: Check if strings in list match very specific conditions
我有一个与此类似的文件名字符串列表(但很长):
list = ['AB8372943.txt', 'test.pdf', '123485940.docx', 'CW2839502.txt', 'AB1234567.txt', '283AB.txt']
我希望通过仅采用符合 4 个条件的字符串来制作另一个列表:
因此,在这种情况下,所需的结果将是此列表:
list2 = ['AB8372943.txt', 'AB1234567.txt']
到目前为止,我知道要检查我可以使用的 7 位数字:
list2 = [i for i in list if re.findall(r"\d{7}", i)]
以及如何在字符串中查找子字符串...但是字符串仅包含子字符串是不够的,它们需要以特定的开头和结尾,并且中间有一个 7 位数字,仅此而已? 有没有办法做到这一点???
非常感谢您!
还要确保它以AB
开头并以.txt
结尾:
my_list = ['AB8372943.txt', 'test.pdf', '123485940.docx', 'CW2839502.txt', 'AB1234567.txt', '283AB.txt']
my_list2 = [i for i in my_list if re.findall(r"^AB\d{7}.txt$", i)]
您应该避免使用像list
这样的内置名称。 此外,如果字符串不包含子字符串,您可以使用re.match
从字符串的开头开始匹配。
AB\d{7}\.txt\Z
模式匹配:
AB\d{7}
匹配 AB 和 7 位数字\.txt
匹配.txt
并注意转义点\Z
字符串结束例如
import re
lst = ['AB8372943.txt', 'test.pdf', '123485940.docx', 'CW2839502.txt', 'AB1234567.txt', '283AB.txt']
lst2 = [s for s in lst if re.match(r"AB\d{7}\.txt\Z", s)]
print(lst2)
Output
['AB8372943.txt', 'AB1234567.txt']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.