Search code examples
regexsearchpattern-matchingdata-processing

Can anyone suggest a regex pattern that matches 4 consecutive lines of text?


I am trying to parse a large data file. In the file there are groups of either 3 or 4 lines of data separated by a blank line. Eg:

Data Group One Name
Data Group One Datum 1
Data Group One Datum 2
Data Group One Datum 3

Data Group Two Name
Data Group Two Datum 1
Data Group Two Datum 2

Data Group Three Name
Data Group Three Datum 1
Data Group Three Datum 2
Data Group Three Datum 3

I am looking for a quick way to extract all groups of data that have 4-lines (ignoring all of the 3-line groups). Is there a way with regex to find all groups of 4-lines in a text file? Or any other suggested (perhaps something using awk or sed) methods to do this?


Solution

  • Not really pretty but this should work:

    /[^\n]+\n[^\n]+\n[^\n]+\n[^\n]+(?!(?:\n[^\n]+))/

    or

    /(?:[^\n]+\n){3}[^\n]+(?!(?:\n[^\n]+))/

    Basically, you're looking for one or more non-new-line characters, then a new line, one or more non-new-line character, then a new line, etc.

    EDIT: Fixed my regex, it matched for blocks of more than 4 lines. I added a negative lookahead for another line of text.