Jack S.
Jack S.

Reputation: 2793

find a string within a tag without finding the tag in python

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

Answers (3)

Artsiom Rudzenka
Artsiom Rudzenka

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

Demian Brecht
Demian Brecht

Reputation: 21368

group(0) is the entire match. You want group(1).

http://ideone.com/Q9sUt

Upvotes: 2

.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

Related Questions