3

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
MMM
  • 425
  • 1
  • 7
  • 24

1 Answers1

3

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  '
heemayl
  • 39,294
  • 7
  • 70
  • 76