a simple RegExp question

  • Thread starter S. Levent Yilmaz
  • Start date
S

S. Levent Yilmaz

Hello,

It sounded like a very simple problem but I couldn't come up with an
elegant solution. The problem is:

Find all lines which contain a given word (say 'kitty') not preceded
with another given word (say 'puppy') . For instance:

I have two pets:
my kitty is very cute
but puppy is cuter than kitty

What regular expression stands only for the 2nd line? Note that the
other way around is very easy, that is the lines with 'puppy' followed
by 'kitty' is only "puppy.*kitty"
Is this possible at all with a single RegExp?

thank you so very much!
-Levent.
 
G

Gunnar Hjalmarsson

S. Levent Yilmaz said:
Find all lines which contain a given word (say 'kitty') not
preceded with another given word (say 'puppy') . For instance:

I have two pets:
my kitty is very cute
but puppy is cuter than kitty

What regular expression stands only for the 2nd line? Note that the
other way around is very easy, that is the lines with 'puppy'
followed by 'kitty' is only "puppy.*kitty"
Is this possible at all with a single RegExp?

Don't know, but why not just do:

/\bkitty\b/ and !/\bpuppy\b.*\bkitty\b/
 
R

Richard Morse

S. Levent Yilmaz said:
Hello,

It sounded like a very simple problem but I couldn't come up with an
elegant solution. The problem is:

Find all lines which contain a given word (say 'kitty') not preceded
with another given word (say 'puppy') . For instance:

I have two pets:
my kitty is very cute
but puppy is cuter than kitty

What regular expression stands only for the 2nd line? Note that the
other way around is very easy, that is the lines with 'puppy' followed
by 'kitty' is only "puppy.*kitty"
Is this possible at all with a single RegExp?

thank you so very much!
-Levent.

You're looking for negative look-behind assertion. (I think).

perldoc perlre

look for "look-behind".

Short form:

my $line =~ m/(?<!puppy).*kitty/;

HTH,
Ricky
 
G

Gunnar Hjalmarsson

Richard said:
You're looking for negative look-behind assertion. (I think).

Think? How about testing the code before posting?
Short form:

my $line =~ m/(?<!puppy).*kitty/;

That matches any line containing "kitty".
 
M

Matt Garrish

Gunnar Hjalmarsson said:
Don't know, but why not just do:

/\bkitty\b/ and !/\bpuppy\b.*\bkitty\b/

Or if the OP had bothered to read a bit of perlre:

/\bkitty\b/ and $` !~ /\bpuppy\b/

Matt
 

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,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top