How to replace a certain string sentence in Python? Using re.sub ()

0

I would like to replace every expression that starts with the characters: *: .

tentativa = 'Olá td bem? *:palavra_proibida*985 td otimo'
resultado = re.sub('*:', '', tentativa)

Result Obtained:

Olá td bem? palavra_proibida*985 td otimo

Expected result:

Olá td bem? td otimo
    
asked by anonymous 03.09.2018 / 23:18

1 answer

1
>>> import re
>>> tentativa = 'Olá td bem? *:palavra_proibida*985 td otimo'
>>> resultado = re.sub(r'\*:\S+', '', tentativa)
>>> print(resultado)
Olá td bem?  td otimo

This code uses \S+ which means "1 or more non-space characters"; It means that it will replace everything that comes after *: until you find the first space.

Note that I also added a slash before * to "escape" the special behavior that * has in regular expressions - with the bar it will be treated only as a normal asterisk to be found.     

03.09.2018 / 23:39