[英]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.