$text = "The dog is black cat is white and the fox does not like the cow or pig";
if ($text =~ /(dog|cow|pig)/) { print "match found" }
Does the match quit once it finds the first occurence of one of the alternatives ? e.g. in this case it finds a match on dog so exits /(dog|cat|fox|cow|pig)/gWill that then try and match each alternative in the string and then return ?
The dog is black cat is white and the fox does not like the cow or pigCan I do that using the alternation (dog|cat|fox|cow|pig) ?
'Does the match quit once it finds the first occurence of one of the alternatives?'
'Will that then try and match each alternative in the string and then return?'
'Can I do that using the alternation ..'
$text = "The dog is black cat is white and the fox does not like the cow or pig"; $text =~ s/(dog|cow|cat|pig)/\n$1/g; print $text;
($1 contains the value matched by the pattern, so you are replacing each match with itself, prepended by \n).
--------------------------------------------------------------
"If there is such a phenomenon as absolute evil, it consists in treating another human being as a thing."
John Brunner, "The Shockwave Rider".
$text =~ s/\b(dog|cat|fox|cow|pig)\b/\n$1/g;Otherwise, you'd match stuff like "cowardly" and "pigheaded" ;)
For the sake of performance, you should switch REGEX alternation with short-circuit alternation:
my $text = 'The dog is black cat is white and the fox does not like the cow or pig'; print 'match found', "\n" if ( $text =~ /dog/ || /cow/ || /pig/ );
This works fine for simple patterns like you're using. The Camel books has a nice explanation for that in Common Pratices chapter.
local $_ = 'The dog is black cat is white and the fox does not like the cow or pig'; print "match found\n" if /dog/ || /cow/ || /pig/; # or by explicitly stating print "match found\n" if $text =~ /dog/ || $text =~ /cow/ || $text =~ /pig/;It is worth noting that alternation in regexen can be expensive but [demerphq]'s patch to bleed perl (and hopefully the recently released 5.8.8) can make it much less so.
Cheers - [Limbic~Region|L~R]
In list context the regex returns all the matches.
#!/bin/perl5 use strict; use warnings; my $text = "The dog is black cat is white and the fox does not like the cow or pig"; my (@array) = $text =~ /(cow|dog|pig)/g; print "@array\n"; __DATA__ ---------- Capture Output ---------- > "C:\Perl\bin\perl.exe" _new.pl dog cow pig > Terminated with exit code 0.
perlmonks.org content © perlmonks.org and Anonymous Monk, g0n, glasswalk3r, Limbic~Region, McDarren, wfsp
prlmnks.org © 2006 edmund von der burg (eccles & toad)
v 0.03