Reputation: 2793
I have a string within a tag that I want to extract without finding the tag too. I tried:
string = re.search("\[tag\](.*?)\[tag\]", "[tag]string[tag]")
print(string.group(0))
and
string = re.search("/\[tag\](.*?)\[tag\]/i", "extra[tag]string[tag]extra")
print(string.group(0))
both return
[tag]string[tag]
Upvotes: 1
Views: 198
Reputation: 29103
You can also use positive lookahead/lookbehind:
import re
text = """
[tag]string[tag]
[tag]string1[tag]
[tag]string2[tag]
[tag]string3[tag]
[tag]string4[tag]
"""
print re.findall(r'(?i)(?<=\[tag\])\w*(?=\[tag\])', text)
Upvotes: 1
Reputation: 129755
.group(0)
is the entire match. Use .group(1)
to get the section in parentheses that you want.
import re
string = re.search("\[tag\](.*?)\[tag\]", "[tag]string[tag]")
print string.group(1) # prints 'string'
Upvotes: 6