john
john

Reputation: 33

regular expression negative look-ahead assertion

i want to filter a set of keys and values. all keys and values whose keys are not aa or aaa should be matched. currently neither the keys are matched, nor are the keys aa and aaa excluded.

reg exp: (?!AA|AAA):.+?;

test string: AA:1;AB:2;AC:3;AAA:4;AAB:5;AAC:6;

expected: AB:2;AC:3;AAB:5;AAC:6;

example: https://regex101.com/r/AyW9PY/1/

i'm grateful for any help.

Upvotes: 3

Views: 29

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626825

The lookahead construct is zero-width, it does not consume the text its pattern matches. Hence, your (?!AA|AAA) just says: if there is AA or AAA immediately to the right, fail the match. But the next char to consume is :, so that lookahead always returns true, and is redundant.

If your keys consist of word chars, you may use

\b(?!AAA?:)\w+:[^;]*;

See the regex demo

Details

  • \b - a word boundary
  • (?!AAA?:) - a negative lookahead failing the match if, immediately to the right of the current location, there are two or three As followed with :
  • \w+ - 1+ word chars
  • : - a :
  • [^;]* - 0+ chars other than ;
  • ; - a ;.

Upvotes: 2

Related Questions