Akshaya Nambiar
Akshaya Nambiar

Reputation: 1

How to grep for a particular pattern exactly two times in perl?

I have a pattern, Let it be this,

pppoe lg id 827 vlan-id 100 pppoe user@local local Jan 3 14:41:20

from this i wanted to grep for the pattern 'pppoe' and want to ensure that it is present exactly two times.

pppoe lg id 827 vlan-id 100 pppo user@local local Jan 3 14:41:20

here pppoe is present only once, other is pppo, this time it should not match.

Upvotes: 0

Views: 113

Answers (3)

Borodin
Borodin

Reputation: 126722

All that is necessary is

if ($str =~ /pppoe.*pppoe/) {
  ...
}

Upvotes: 0

Sujith PS
Sujith PS

Reputation: 4864

You can use :

^((?!pppoe).)*(pppoe)((?!pppoe).)*\2((?!pppoe).)*$

Refer Demo

Explanation :

Explanation

Upvotes: 0

grebneke
grebneke

Reputation: 4494

A straight forward way is to put the matches in an array and check the number of items:

my $str = "pppoe lg id 827 vlan-id 100 pppoe user\@local local Jan 3 14:41:20";
my @count = $str =~ /pppoe/g;
if (scalar @count == 2) {
    print "MATCH exactly two times\n";
}

or, as suggested by mpapec:

print "MATCH\n" if scalar @{[ $str =~ /pppoe/g ]} == 2;

Upvotes: 4

Related Questions