Samiya Qureshi
Samiya Qureshi

Reputation: 81

How do I match the line before matched pattern using regular expression

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

This code gives the line after the matched pattern how can I get line before the matched pattern?

Upvotes: 1

Views: 4251

Answers (1)

Adam Smith
Adam Smith

Reputation: 54163

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

I don't know matlab, but it makes sense.

(?m) tells ^ and $ to match at beginning and end of line rather than beginning and end of string, ^(.*)$ captures any entire line and (?=\n^abc&) asserts that whatever follows that line is a newline character, then the beginning of a line, and a literal abc&. It may require some tweaking to work in matlab, but that seems to be what you're looking for.

Note that since I don't know matlab, there's quite possibly a better way to do this. For instance in Python I would do something like:

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

Which doesn't need to use any fancy regex at all, just reading a file line-by-line.

Upvotes: 2

Related Questions