Python 正则表达式 : Get regex pattern in a text file and store in an array or list

标签 python regex text

我在文本文件中有此示例数据:

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/

相关文章:

python - 将 Pandas 时间戳四舍五入到分钟

Python - 如何使用 BeautifulSoup 将一个类定位到另一个类中?

java - 我应该如何限制 ANTLR 中 ID token 的长度?

Java,图像上的文本,更新

mysql - Sphinx 搜索引擎的首字母缩略词

css如何使用带省略号的div实现多行文本字段

python - 使用随机二进制 key 解密二进制序列。我的脚本有什么问题?

regex - 为什么在使用带有否定字符集的星号时不进行回溯

regex - 将 24 小时格式的时间与正则表达式匹配

python - Django:选择具有最大时间戳的值或加入同一个表