我有一個名稱如下的檔案串列。
["TYBN-220422-257172171.txt", "TYBN-120522-257172174.txt", "TYBN-320422-657172171.txt", "TYBN-220622-237172174.txt", "TYBN-FRTRE-FFF.txt",....]
我只想獲取具有這樣格式的檔案TYBN-220422-257172171.txt
valid = "TYBN-{}-{}".format(numericvalue, numericvalue)
我只想要串列中的這種型別的檔案。
uj5u.com熱心網友回復:
正則運算式解釋:
- ^字串的開頭
- $字串結尾
- \d匹配所有數字。相當于 [0-9]
- 一個或多個運算式
import re
files = ["TYBN-220422-257172171.txt", "TYBN-120522-257172174.txt"]
pattern = re.compile("^TYBN-\d -\d \.txt$")
for f in files:
if pattern.match(f):
print(f " matched naming convention.")
uj5u.com熱心網友回復:
這可能最容易使用正則運算式來匹配所需的格式,即
TYBN-\d -\d \.txt$
它查找以字符開頭的名稱,TYBN-
后跟一個或多個數字 ( \d
)、a -
、更多數字,然后以 . 結尾.txt
。
請注意,使用時re.match
(如下面的代碼),匹配項會自動錨定到字串的開頭,因此^
正則運算式不需要前導(字串開頭的錨點)。
在蟒蛇中:
import re
filelist = ["TYBN-220422-257172171.txt",
"TYBN-120522-257172174.txt",
"TYBN-320422-657172171.txt",
"TYBN-220622-237172174.txt",
"TYBN-FRTRE-FFF.txt"
]
regex = re.compile(r'TYBN-\d -\d \.txt$')
valid = [file for file in filelist if regex.match(file)]
輸出:
[
'TYBN-220422-257172171.txt',
'TYBN-120522-257172174.txt',
'TYBN-320422-657172171.txt',
'TYBN-220622-237172174.txt'
]
uj5u.com熱心網友回復:
試試這個。
lst = ["TYBN-220422-257172171.txt", "TYBN-120522-257172174.txt", "TYBN-320422-657172171.txt", "TYBN-220622-237172174.txt", "TYBN-FRTRE-FFF.txt"]
valid_format = ['TYBN',True,True] # here true for digits
valid = []
for a in lst:
l = a.replace('.txt','').split('-')
if l[0] == valid_format[0]:
if [i.isdigit() for i in l[1:]] == valid_format[1:]:
valid.append(a)
print(valid)
輸出:
['TYBN-220422-257172171.txt',
'TYBN-120522-257172174.txt',
'TYBN-320422-657172171.txt',
'TYBN-220622-237172174.txt']
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/470916.html
標籤:Python python-2.7