正则表达式在多个空行之后捕获文本文件中的信息

时间:2019-06-25 16:12:03

标签: python regex python-3.x

我用python打开了一个复杂的文本文件,将我需要的其他所有内容都与正则表达式进行了匹配,但是却被一次搜索困住了。

我想捕获“从这里开始”行之后的数字。两行之间的空间很重要,并计划在以后拆分。

start after here: test


5.7,-9.0,6.2

1.6,3.79,3.3

代码:

text = open(r"file.txt","r") 
for line in text:
    find = re.findall(r"start after here:[\s]\D+.+", line) 

我在这里https://regexr.com/尝试过,它似乎可以工作,但是它适用于Java。

找不到任何东西。我认为这是因为我需要合并多行,但是不确定如何以其他方式读取文件或合并。一直在尝试对正则表达式进行许多调整,但没有成功。

2 个答案:

答案 0 :(得分:1)

模式start after here:[\s]\D+.+与文字词匹配,然后与[\s]一起使用空格字符(可以省略方括号)。

然后匹配1+次未匹配的数字,该匹配将一直进行到5.7之前。然后将1+次除换行符以外的任何字符都匹配,这将匹配5.7,-9.0,6.2,它将不匹配随后的空行和下一行。

一种选择是匹配字符串,然后匹配所有不以捕获组中的小数点开头的行。

\bstart after here:.*[\r\n]+(\d+\.\d+.*(?:[\r\n]+[ \t]*\d+\.\d+.*)*).*

包括空行在内的值在第一个捕获组中。

例如

import re

regex = r"\bstart after here:.*[\r\n]+(\d+\.\d+.*(?:[\r\n]+[ \t]*\d+\.\d+.*)*).*"

test_str = ("start after here: test\n\n\n"
    "5.7,-9.0,6.2\n\n"
    "1.6,3.79,3.3\n")

matches = re.findall(regex, test_str)

print(matches)

结果

['5.7,-9.0,6.2\n\n1.6,3.79,3.3']

Regex demo | Python demo

如果要在逗号前匹配小数点(或仅一位或多位数字),则可以分割1条或多条换行符,并使用:

[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?=,|$)

Regex demo

答案 1 :(得分:0)

import re

test_str = ("start after here: test\n\n\n"
    "5.7,-9.0,6.2\n\n"
    "1.6,3.79,3.3\n")


m = re.search(r'start after here:([^\n])+\n+(.*)', test_str)
new_str = m[2]
m = re.search(r'(-?\d*\.\d*,?\s*)+', new_str)
print(m[0])