S
sln
I can't seem to get perl to match both the words 'chad' AND 'party'
in the string "chad ttyp0 party". Below is what I attempted.
[cdalten@localhost oakland]$ more match.pl
#!/usr/bin/perl
use warnings;
#$string = `w | grep cdalten | grep telnet`;
$test = "chad ttyp0 party";
if ("$test" =~/(\bchad\b)(\bparty\b)/) {
print "true \n";
}
[cdalten@localhost oakland]$ ./match.pl
[cdalten@localhost oakland]$
What am I doing wrong>
Since you didn't mention an order of appearence, the below
will cover the AND like operator in regexp, on two objects
in ANY order. Otherwise "$test" =~/(\bchad\b).*(\bparty\b)/
would work as many have said on this thread.
It can be done in a single regular expression using a
zero-width negative look-ahead assertion and the two objects.
The basic logic is below. However I think this can be generalized
for AND on sets of 3 or more items using some form of s///eg and/or
a more complex backreferencing scheme, recursion, or other extended
regular expression methods.
-sln
------------------------------------------------------------
## Rx_And.pl
## --
use strict;
use warnings;
my @ar = (
'chad ttyp0 party',
'chad ttyp0 chad',
'party ttyp0 chad',
'party ttyp0 party',
'chad party party ttyp0 chad',
);
for (@ar)
{
# print " Found $1 AND $2\n"
# if ( / (\b chad | party \b) .* (?!\1) (\b chad | party \b) /x );
# Or, for a closer (non-greedy) global examination ..
my $cnt = 1;
print "\n'$_'\n";
while ( / (\b chad | party \b) (.*?) (?!\1) (\b chad | party \b) /xsg ) {
print " Found[",$cnt++,"]: $1 ($2) AND $3\n"
}
}
__END__
'chad ttyp0 party'
Found[1]: chad ( ttyp0 ) AND party
'chad ttyp0 chad'
'party ttyp0 chad'
Found[1]: party ( ttyp0 ) AND chad
'party ttyp0 party'
'chad party party ttyp0 chad'
Found[1]: chad ( ) AND party
Found[2]: party ( ttyp0 ) AND chad