2)need to know how many matches has regex hitThis statement could be interpreted different ways.. Do you want to know how many captures there were (i.e, $1, $2, ...)? Or do you want to see how many times the entire regex is matched globally in the string (i.e, as with m//g)? Judging from #6 above, you seem to mean the former.
From perlop: In list context, m// returns:
This seems to give most of the information you need, with the catch that the last 2 cases overlap (i.e, "1" =~ /(1)/ and "foo" =~ /./ return the same thing in list context, but one has captures and one doesn't). To distinguish between these cases, you can look at @-, as you suggested. It will tell you whether there were captures in the last successful match, so you know how to interpret the return value of the match statement. Finally, to catch the case that the (user-provided) regex is invalid, you can wrap the whole thing in an eval.
Putting it all together:
Output:use strict; my $string = "foobar1"; for my $regex (<DATA>) { chomp $regex; my ($success, @captures); eval { @captures = $string =~ /$regex/; $success = 1 if @captures; @captures = () if $success and @- == 1; }; print "$regex: "; if ($@) { print "invalid regex\n"; ## optionally print $@ here } elsif ($success and @captures) { print "matched: @captures\n"; } elsif ($success and !@captures) { print "matched (no captures)\n"; } else { print "didn't match\n"; } } __DATA__ foo((( (fo(o))(bar) o(.*)a foobar baz(bar)( blah(foo) (.)$
foo(((: invalid regex (fo(o))(bar): matched: foo o bar o(.*)a: matched: ob foobar: matched (no captures) baz(bar)(: invalid regex blah(foo): didn't match (.)$: matched: 1
blokhead
In reply to Re: regex persistence of matches
by blokhead
in thread regex persistence of matches
by spx2
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |