Reputation: 507
I am trying to use regex to remove @tags from a string in python however when i try to do this
str = ' you @warui and @madawar '
h = re.search('@\w*',str,re.M|re.I)
print h.group()
It outputs only the first @tag.
@warui
and when i try it on http://regexr.com?304a6 it works
Upvotes: 1
Views: 192
Reputation: 14534
re.search()
will only match one occurrence of the pattern. If you want to find more, try using re.findall()
.
Upvotes: 3
Reputation: 33509
import re
s = ' you @warui and @madawar '
for h in re.findall('@\w*',s,re.M|re.I):
print h
Prints:
@warui
@madawar
Upvotes: 3
Reputation: 212885
"to use regex to remove @tags from a string"
import re
text = ' you @warui and @madawar '
stripped_text = re.sub(r'@\w+', '', text)
# stripped_text == ' you and '
or do you want to extract them?
import re
text = ' you @warui and @madawar '
tags = re.findall(r'@\w+', text)
# tags == ['@warui', '@madawar']
A @tag is defined as @
followed by at least one alphanumeric character, that's why @\w+
is better than @\w*
. Also you don't need to modify the case-sensitiveness, because \w
matches both lower and upper characters.
Upvotes: 5