如何从文件名中提取子字符串?
我有一个文件夹,里面全是文件,这些文件的名字里都有日期字符串:
file_type_1_20140722_foo.txt
file_type_two_20140723_bar.txt
filetypethree20140724qux.txt
我需要从这些文件名中提取出日期字符串,并把它们保存到一个数组里:
['20140722', '20140723', '20140724']
不过这些日期字符串可能出现在文件名的不同位置,所以我不能直接用简单的字符串截取方法来提取。以前我在Bash里做类似的事情是这样:
date=$(echo $file | egrep -o '[[:digit:]]{8}' | head -n1)
但是我不能用Bash来做这个,因为它在数学运算上不太行(我需要能够进行浮点数的加减运算)。我试过用 glob.glob()
和 re.match()
,但这两个方法都返回了空结果:
>>> dates = [file for file in sorted(os.listdir('.')) if re.match("[0-9]{8}", file)]
>>> print dates
>>> []
我知道问题在于它在找完整的八位数文件名,但我不知道怎么让它去找文件名中的子字符串。有没有什么好主意?
3 个回答
1
re.match
是从字符串的开头开始匹配的,而 re.search
可以在字符串的任何位置找到匹配的内容。
你也可以试试这个:
extract_dates = re.compile("[0-9]{8}").findall
dates = [dates[0] for dates in sorted(
extract_dates(filename) for filename in os.listdir('.')) if dates]
2
你的正则表达式看起来不错,但你应该使用 re.search 而不是 re.match,这样它才能在字符串中的任何位置搜索这个表达式:
import re
r = re.compile("[0-9]{8}")
m = r.search(filename)
if m:
print m.group(0)
6
>>> import re
>>> import os
>>> [date for file in os.listdir('.') for date in re.findall("(\d{8})", file)]
['20140722', '20140723']
注意,如果一个文件名中有9位数字的部分,那么只会匹配前面的8位数字。如果文件名中有16位数字的部分,那么会有2个不重叠的匹配结果。