如何使用正则表达式匹配匹配模式之前的行

时间:2014-08-20 12:22:20

标签: regex matlab pattern-matching fopen getline

y=regexp(fid,'^abc&')
z=fgetl(fid)
fprintf('%s',z)

此代码给出匹配模式之后的行,如何在匹配模式之前获取行?

1 个答案:

答案 0 :(得分:2)

y = regexp(fid, '(?m)^(.*)$(?=\n^abc&)')

我不知道matlab,但它是有道理的。

(?m)告诉^$在行的开头和结尾匹配,而不是字符串的开头和结尾,^(.*)$捕获任何整行和(?=\n^abc&)断言该行后面的任何内容都是换行符,然后是行的开头,以及文字abc&。可能需要一些调整才能在matlab中工作,但这似乎是你正在寻找的。

请注意,由于我不了解matlab,因此很可能有更好的方法。例如在Python中我会做类似的事情:

lines = [] # make an empty list

with open('path/to/file.txt') as in_file:
    curr = next(in_file) # reads a line from the file to prime the loop
    while True: # infinite loop
        prev = curr
        try:
            curr = next(infile) # read a line from the file
        except StopIteration:
            break # jump out of the loop when the file is exhausted
        if re.search('^abc&', curr): # if the current line matches pattern
            lines.append(prev) # toss the previous line in our list
        # then loop

根本不需要使用任何花哨的正则表达式,只需逐行读取文件。

相关问题