Regex question. Oh I so cannot do regular expression matching.

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top