Trying to wrap my head around look-ahead and look-behind in regex processing.
Let's assume I have a file listing PIDs and other things. I want to build a regex to match the PID format \d{1,5} but that also excludes a certain PID.
$myself = $$;
@file = `cat $FILE`;
@pids = grep /\d{1,5}(?<!$myself)/, @file;
In this regex I try to combine the digits match with the exclusion using a negative look-behind by using the (?<!TO_EXCLUDE) construct. This doesn't work.
Sample file:
456
789
4567
345
22743
root
bin
sys
Would appreciate if someone could point me in the right direction.
Also would be interested to find out if this negative look-behind would be the most efficient in this scenario.
"Look behind" really looks behind. So, you can check whether a PID is preceded by something, not whether it matches something. If you just want to exclude $$, you can be more straightforward:
@file = `cat $FILE`;
@pids = grep /(\d{1,5})/ && $1 ne $$, @file;