Python regex to remove emails from string

Viewed 19496

Need to replace emails in a string, so:

inp = 'abc user@xxx.com 123 any@www foo @ bar 78@ppp @5555 aa@111"

should result in:

out = 'abc 123 foo bar"

What regex to use?

In [148]: e = '[^\@]\@[^\@]'
In [149]: pattern = re.compile(e)
In [150]: pattern.sub('', s)  
Out[150]: 'one aom 123 4two'
In [151]: s
Out[151]: 'one ab@com 123 4 @ two'

Does not work for me

4 Answers

Adding as nobody as added a regex :

text= 'abc user@xxx.com 123 any@www foo @ bar 78@ppp @5555 aa@111'

required_output=re.sub(r'[A-Za-z0-9]*@[A-Za-z]*\.?[A-Za-z0-9]*', "", text)
    
required_output=" ".join(required_output.split())
Related