Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negative pattern matching Reg ex In Python

Tryto use negative forward to replace all string which does not match a pattern:

regexPattern = '((?!*' + 'word1|word2|word3' + ').)*$'  
mytext= 'jsdjsqd word1dsqsqsword2fjsdjswrod3sqdq'
return re.sub(regexPattern, "P", mytext)

#Expected Correct Output:  'PPPPPPword1PPPPPPword2PPPPPword3PPP'

#BAD Output:  'jsdjsqd word1dsqsqsword2fjsdjswrod3sqdq'

I try this but it does not work (string remains same). How to modify it ? (think this is pretty difficult regex)


1 Answers

You can use

import re
regex = re.compile(r'(word1|word2|word3)|.', re.S)
mytext = 'jsdjsqd word1dsqsqsword2fjsdjsword3sqdq'
print(regex.sub(lambda m: m.group(1) if m.group(1) else "P", mytext))
// => PPPPPPPPword1PPPPPPword2PPPPPPword3PPPP

See the IDEONE demo

The regex is (word1|word2|word3)|.:

  • (word1|word2|word3) - either word1, or word2, or word3 character sequences
  • | - or...
  • . - any character (incl. a newline as re.S DOTALL mode is on)

See the regex demo

like image 160
Wiktor Stribiżew Avatar answered Mar 25 '26 09: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!