开发者

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

开发者 https://www.devze.com 2023-03-26 02:55 出处:网络
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:

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 o开发者_高级运维f 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?


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.


I haven't tested it, but this should work for an awk script:

#!/bin/awk -f
BEGIN {
        count = 0;
        lines = "";
}
{    
    if ($0 != "") {
        lines = lines \n $0;
        count++;
    } else if (count == 4) {
        print lines;       
    }
    if ($0 == "") {
        count = 0;
        lines = "";
    }
}


You could work around line break characters - pseudo code example:

\n\n 1-or-more-characters \n 1-or-more-characters \n 1-or-more-characters \n 1-or-more-characters \n\n


(?:.+\n){1,3}

this will capture 1 line, 2 lines and 3 lines.

this is greedy matches.

if you need 3 or 4 lines you can use:

(?:.+\n){3,4}

or you can use:

(?:[^\n]+\n){3,4}

I have tested it in https://regex101.com/

0

精彩评论

暂无评论...
验证码 换一张
取 消