Nissim
Nissim

Reputation: 6553

Regex expression to exclude both prefix and suffix

I'm trying to build an expression which will match all text EXCLUDING text with prefix 'abc' AND suffix 'def' (text which only has the prefix OR the suffix is ok).

I've tried the following: ^(?!([a][b][c]])).*(?!([d][e][f])$), but it doesn't match text which only has one of the criterias (i.e. abc.xxx fails, as well as xxx.pdf, though they should pass)

I understand the answer is related to 'look behind' but i'm still not quite sure how to achieve this behavior

I've also tried the following: ^(?<!([a][b][c])).*(?!([d][e][f])$), but again, with no luck

Upvotes: 3

Views: 7736

Answers (2)

Sebastian Proske
Sebastian Proske

Reputation: 8413

Keep it simple and combine it into a single lookahead to check both conditions:

^(?!abc.*def$).*

Upvotes: 3

G&#225;bor Fekete
G&#225;bor Fekete

Reputation: 1358

^((abc.*\.(?!def))|((?!abc).*\.def))$

I think there can be a simpler solution, but this one will work as you wanted it.

[a][b][c] can be simplified to abc, the same goes for def. The first part of the pattern matches abc.*\. without def at the end. The second part matches .*\.def without the prefix abc.

Here is a visual representation of the pattern:

Regular expression visualization

Debuggex Demo

Upvotes: 3

Related Questions