tags:

views:

100

answers:

2

Hi, I've been trying to do the following:

 if (m/(foobar)\{2,}?/ig)

to process a file and only act on those lines where greater than 2 occurences of 'foobar' are present. Not working - I suspect it may need the "back-referencing" technique, but I'll be pleasantly surprised if someone here can do it with a simple matching technique

+7  A: 

You can't use the {} quantifiers because that's only for repeats. (e.g. "foobar foobar foobar"). If your string had "fooobar more foobar" it wouldn't match. The easiest and clearest way is do it by shoving the matches into an array like this:

 my @matches = $str =~ /(foobar)/ig;

Then @matches would hold all the matches.

if (@matches >=2) {
   # work in special sauce
}
seth
That seems to be exactly what I was after! I understand the {} quantifiers a little more now - Thanks.
DBMarcos99
You are welcome
seth
+7  A: 

it's pretty simple:

if ( $str =~ /foobar.*foobar/ ) {

Of course - your foobar might be a bit complex, so let's use backreference:

if ( $str =~ /(foobar).*\1/ ) {

And what if you'd want to have it matched only if this is 5 times in line? Simple:

if ( $str =~ /(foobar)(.*\1){4}/ ) {

or better:

if ( $str =~ /(foobar)(?:.*\1){4}/ ) {

For details on ?: and other such magical strings, you can chech perldoc perlre.

depesz
Thx for this. I'm putting this as my accepted answer as you gave more than one solution (even though Seth's answer is great too). Thx, Mark
DBMarcos99