What can be a possible regex to match any of the following:
Eggs and Legs
Legs and Eggs
I can only think of the following regex:
(Eggs|Legs) and (Eggs|Legs)
But i want to avoid matching:
Eggs and Eggs
Legs and Legs
PS: Edited my solution to add parenthesis,
Use a capturing group and negative lookahead:
/(Eggs|Legs) and (?!\1)(?:Eggs|Legs)/
I.e. the first and the last word can be Eggs or Legs, but capture the first word (using (...)), and then make sure and isn't followed by that word (using negative lookahead ((?!...)) for whatever the first word was (\1)).
See it in action here.
This will capture both words surrounding and and will print them both unless the first captured word is the same as the second one:
use strict;
use warnings;
open my $in, '<', 'in.txt';
while(<$in>){
chomp;
my ($match1, $match2) = /(\w+) and (\w+)/;
print "$match1\t$match2\n" unless $match1 eq $match2;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With