我在文本文件中有此示例数据:
09-02||||||||09-14|07:24|12:15|12:58| | |
09-03| | | | | | |09-15|||||||
我试图获取具有这种模式的所有数据并将其存储在数组或列表中:
\d{2,3}-\d{2,3}
打印时的输出数据应该是这样的:
['09-02','09-14','09-02','09-15']
我尝试了这段代码,但它打印了与模式匹配的所有行:
n_date = re.compile('\d{2,3}-\d{2,3}')
with open('sample_2.txt', 'r') as n:
for line in n:
re.match(n_date, line)
print(line)
请给我一个想法,如何才能获得与我的正则表达式模式匹配的数据而不是整行。谢谢!
最佳答案
试试这个:
import re
n_date = re.compile('\d{2,3}-\d{2,3}')
with open('sample_2.txt', 'r') as n:
n = n.read()
result = re.findall(n_date, n)
print(result)
打印出来:
['09-02', '09-14', '09-03', '09-15']
您的代码仅打印 for 循环的最后一行,并且您没有存储或使用 re.match
的结果。 re.findall
将为您提供所需的内容,即与模式匹配的所有元素的列表。
关于Python 正则表达式 : Get regex pattern in a text file and store in an array or list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52638349/