1

Example buffer:

Line 1 is my favourite line
Line 2 is bad
Line 3 is bad
Line 1 is still my favourite line

How do I use regex to match the 2 sentences that contain "Line 1" ?

Please note that the number '1' is not known to me, Only thing that's known is that the multiple occurences have the same number.

2 Answers 2

1
my $s = q{Line 1 is my favourite line
Line 2 is bad
Line 3 is bad
Line 1 is still my favourite line
};

my ($l1, undef, $l2) = $s =~ /(Line \s* ([0-9]+) .*) [\w\W]*? (Line \s* \2 .*)/x;
print "$l1\n$l2\n";

output

Line 1 is my favourite line
Line 1 is still my favourite line
Sign up to request clarification or add additional context in comments.

2 Comments

Hello mpapec, could you elaborate a little as I don't have the exact same usecase and will need to understand what you've done to implement it.
@Proteen it looks for two lines with same number (note \2 which is reference to ([0-9]+)). If you need something more complex, regex is probably not right tool for the job.
0
use 5.14.0; #including features 'say' and smart match (~~)
use warnings;


my @lines = (); #lines that occurred

while (<DATA>){
    my $line = /^(Line\s*+\d+\b)/ ? $1 : ''; #\b to avoid '2' matches '22'
    $line ~~  @lines and do {say "$line occurred before."; next;}; 
    push @lines, $line;
}


__DATA__
Line 1 is my favourite line
Line 2 is bad
Line 3 is bad
Line 1 is still my favourite line
Line 22 is bad

Output:

Smartmatch is experimental at ./tst.pl line 16.
Line 1 occurred before.

Whilst the above code is good to pick up line numbers that have occurred, it doesn't tell you what those lines are. If you do want that feature, then try the following code:

my @lines = ();

while (<DATA>){
    my $line = /^(Line\s*+\d+\b)/ ? $1 : ''; #\b to avoid '2' matches '22'
    next unless $line;
    push @lines, $_;
    my @occurred = grep {/$line/} @lines;
    @occurred > 1 and print for @occurred;
}

Output:

Line 1 is my favourite line
Line 1 is still my favourite line

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.