Persson
Persson

Reputation: 422

Remove everything after @ til next space until no more matches are found?

I have a string looking like this: Hello @StackOverflow! How are you today? I'd like to !sh @StackExchange

I would like it to look like this: Hello ! How are you today? I'd like to !sh

I would like to remove @ and anything after it, until the string is cleared of all matches.

The solution I came up with only removes the first occurence.

re.sub('@\S+ ', '', myString)

Upvotes: 1

Views: 61

Answers (2)

anubhava
anubhava

Reputation: 785196

You may use this re.sub:

@\w+\s*

Code:

>>> s = "Hello @StackOverflow! How are you today? I'd like to !sh @StackExchange"
>>> print ( re.sub(r'@\w+\s*', '', s) )
Hello ! How are you today? I'd like to !sh

RegEx Details:

  • @: Match literal @:
  • \w+\s*: Match 1+ word characters followed by 0 or more whitespaces

Upvotes: 1

Advay168
Advay168

Reputation: 627

You just need to remove the trailing space in your string.

import re
myString = "Hello @StackOverflow! How are you today? I'd like to !sh @StackExchange"
re.sub('@\S+', '', myString)

Upvotes: 1

Related Questions