简体   繁体   中英

Regex lookbehind position of words

The thing was not very nice.

My regex so far:

(?<!not\s)(?<!n't\s)(nice|friendly|excelent|comfortable|easy access|good|clean|beautiful)

I want to match only words (nice,friendly... in this sentence...) if the sentence does not contain words: "not" or "n't" (aka wasn't, isn't). Aka positive sentences.

But this regex works only for sentences like:

The thing was very not nice.

How to write lookbehind to check if the words "not" or "n't" are not in whatever position before my adjectives?

You could use a negative look ahead to check there isn't any not or n't anywhere in the string, and \\K to throw out the part you don't want:

^(?!.*(?:not|n't)).*\K(nice|friendly|excellent|comfortable|easy access|good|clean|beautiful)

(?!...) will fail if what's inside it matches, (?:not|n't) is a non capturing group.

Kind in mind that this is a pretty simple check though. It wouldn't match nice in This is nice but not pretty . If you want to add more in depth syntax understanding, you'll have to dig deeper.

Lookbehinds must be fixed-length.

It would perhaps be easier to divide the task. First check if the sentence contains "nice", "friendly" etc., and then in a separate conditional, check if it doesn't contain a negation.

This would make it easier to detect double-negatives too :p

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM