DBMarcos99
DBMarcos99

Reputation: 465

Is there a simple way to match more than 1 occurence of a specified string on each line?

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

Upvotes: 1

Views: 147

Answers (2)

user80168
user80168

Reputation:

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.

Upvotes: 7

seth
seth

Reputation: 37267

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
}

Upvotes: 7

Related Questions