Search code examples
pythonregexreplacenegation

re.sub with exception or condition


I want to sub use re.sub to substitute all the words with parentheses but not the word (k), I want to use some negation conditions but it seems not working to my example.

I've tried

 \((?<!k)\w+\)

Is there any suggestions?

re.sub(r'\((?<!k)\w+\)', '', '(k) i am, us dep economy (applause) (ph)', flags= re.IGNORECASE)      

Desired result would be

(k) i am, us dep economy

Solution

  • Use a negative lookahead:

    \((?!k\))\w+\)
    
    • (?!k\) makes sure k) does not come after the initial (

    So:

    In [75]: re.sub(r'\((?!k\))\w+\)', '', '(k) i am, us dep economy (applause) (ph)', flags= re.IGNORECASE)
    Out[75]: '(k) i am, us dep economy  '