收录日期:2019/03/20 19:58:00 时间:2009-07-29 18:31:52 标签:regex,perl

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

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.

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
}