Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression negative look-ahead assertion

Tags:

regex

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.

like image 288
john Avatar asked Mar 10 '26 04:03

john


1 Answers

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 ;.
like image 185
Wiktor Stribiżew Avatar answered Mar 17 '26 06:03

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!