Scorpion
Scorpion

Reputation: 3976

Regex matches during look behind

I am using the regex below to match strings; I was expecting the following results

Regex ^.*(?<!abc)(?<!def)(?<!ghi).xyz.co.*

Not Match

    ghi.xyz.org
    ghi-hipqr.xyz.org
    abc-hipqr.xyz.org

Match

qrs.xyz.org
qrs-hipqr.xyz.org

However, ghi-hipqr.xyz.org is matching the regex (it shouldn't have since there is a look behind for the string ghi which is present in the string. How can I fix it?

Upvotes: 1

Views: 38

Answers (1)

anubhava
anubhava

Reputation: 784958

It is failing because ghi is not immediately before .xyz. in your string. Java (like many more regex engines) doesn't support variable length negative length look-behind assertion.

You can use this negative lookahead expressions instead:

^(?!.*\b(?:abc|def|ghi)\b).*\.xyz\.org.*$

RegEx Demo

Upvotes: 1

Related Questions