【发布时间】:2018-09-27 06:35:40
【问题描述】:
此代码 sn-p 旨在在提供的文件的每一行上搜索正则表达式匹配。 re.search() 在文件中包含 3e+5 次“#”字符的行处挂起。
有什么办法可以解决这个问题?
import re
print "Started..."
exp = "(.*)\$\$\$Uniqueterm:(.*)"
with open("sample.txt", 'r') as file:
for line in file:
if re.search(exp, line):
print "Found match: " + re.search(exp,line).groups()[1].strip()
print "File finished..."
示例输入文件(sample.txt):
abc
pqr
##### (3e+5 times '#' in a single line)
xyz
$$$Uniqueterm: Match it
qaz
预期输出:
Match it
【问题讨论】:
-
sample.txt有多大? -
您要匹配的实际数据是什么?您的正则表达式模式与示例数据完全不匹配。
-
添加了我要匹配的示例数据。文件大小为 3.84 MB,与问题提供的数据完全相同。
-
运行完全发布的代码会产生挂起吗?
-
是的,它提供以下输出,然后挂起:“开始...”。如果我们删除包含 "#"s 的行,我们会得到预期的输出。
标签: python regex python-2.7