Regular expression - negative look ahead

I am trying to use the Perl negative look-ahead regex to exclude a specific line from the target line. Please give me your advice.

I tried to get strings that don't have -sm, -sp or -sa.

REGEX:

hostname .+-(?!sm|sp|sa).+ 

ENTRANCE

 hostname 9amnbb-rp01c hostname 9tlsys-eng-vm-r04-ra01c hostname 9tlsys-eng-vm-r04-sa01c hostname 9amnbb-sa01 hostname 9amnbb-aaa-sa01c 

Expected Result:

 hostname 9amnbb-rp01c - SELECTED hostname 9tlsys-eng-vm-r04-ra01c - SELECTED hostname 9tlsys-eng-vm-r04-sa01c hostname 9amnbb-sa01 hostname 9amnbb-aaa-sa01c 

However, I got this actual result below:

 hostname 9amnbb-rp01c - SELECTED hostname 9tlsys-eng-vm-r04-ra01c - SELECTED hostname 9tlsys-eng-vm-r04-sa01c - SELECTED hostname 9amnbb-sa01 hostname 9amnbb-aaa-sa01c - SELECTED 

Please help me.

ps: I used Regex Coach to visualize my result.

+4
source share
2 answers

Move .+- inside the viewing window:

 hostname (?!.+-(?:sm|sp|sa)).+ 

Rubular: http://www.rubular.com/r/OuSwOLHhEy

Your current expression does not work correctly, because when .+- is outside the lookahead, it can go back until lookahead no longer causes the regular expression to fail. For example, with the string hostname 9amnbb-aaa-sa01c and the regular expression hostname .+-(?!sm|sp|sa).+ , The first .+ Will match 9amnbb , lookahead will see aa as the next two characters and continue, and the second .+ woudl match aaa-sa01c .

An alternative to my current regex would be this:

 hostname .+-(?!sm|sp|sa)[^-]+?$ 

This will prevent backtracking, since after viewing it may occur not - but not greedy ? for this to work correctly in multi-line global mode.

+4
source

The following are your test files:

 hostname [^-]+(-(?!sm|sp|sa)[^-]+)+$ 

I think this is a little easier to read than F.J.

To answer Rudi: the question was asked as an exception situation. This seems to be well suited for a negative look. :)

+1
source

Source: https://habr.com/ru/post/1416422/


All Articles