1myb
1myb

Reputation: 3596

Python regular syntax remove @ string until space

I tried to google some but it's too specific and i'm totally new to regular expression of python. May i know how can i remove the entire string after symbol @ until it next space? while this is what i do but no luck

s = re.sub('@[^\s]+', '',s)

Upvotes: 1

Views: 1798

Answers (4)

nameless
nameless

Reputation: 1979

What about the following regex?

re.sub(r'@.*?(?=\s)', '', s)

Example:

>>> re.sub(r'@.*?(?=\s)', '', 'text before `at`@text-right-arter`at` text after first space')
'text before `at` text after first space'
>>> 

It behaves exactly like your solution though (Update: not actually true. See the nhahtdh's comment below).

Upvotes: 1

Tuim
Tuim

Reputation: 2511

From what you gave as input and context.

re.sub('@\S* ','',string)

See here http://codepad.org/8KmXy7aW

Upvotes: 0

Kent
Kent

Reputation: 195079

I think it doesn't work for you because you removed '@' as well.

i remove the entire string after symbol @ until it next space

try this:

In [1]: s='foo@barxyz trash trash'

In [2]: import re

In [3]: re.sub('(?<=@)[^\s]+','',s)
Out[3]: 'foo@ trash trash'

Upvotes: 1

Inbar Rose
Inbar Rose

Reputation: 43447

i think this is what you want:

>>> import re
>>> s = 'unchanged1 @remove unchanged2'
>>> print re.sub('@\S+', '', s)
unchanged1  unchanged2

according to OP: 'remove the entire string after symbol @ until it next space'

to remove the extra space:

>>> print re.sub('@\S+ ', '', s)
unchanged1 unchanged2

to include the '@':

>>> print re.sub('@\S+ ', '@', s)
unchanged1 @ unchanged2

Upvotes: 0

Related Questions