Regular expression to extract text in python

Question:

I am new using the re library and I would like to know if somebody knows how to extract the following text:

Initial

'[p]I am a test paragraph[/p]'

Output

I am a test paragraph

I tried to use the following line :

text = '[p]I am a test paragraph[/p]'
param = re.findall("[p](.*?)[/p]]", text)

but the output was :

>>[']I am a test paragraph[/']

I tried to used the BBCode library but it doesn’t work with this kind of text.

Asked By: Van Jake

||

Answers:

# regex to extract text between [p] and [/p] tags
regex = r'[p](.*?)[/p]'
test_text = '[p]I am a test paragraph[/p]'

# extract text between [p] and [/p] tags
list_of_results = re.findall(regex, test_text)
Answered By: Charles Yang
import re
text = '[p]I am a test paragraph[/p]'
parm = re.findall(r'[p](.*?)[/p]', text)[0]  
print(parm)

Gives #

I am a test paragraph

or simply uisng rfind

text = '[p]I am a test paragraph[/p]'

start = '[p]'
end = '[/p]'

print (text[text.find(start)+len(start):text.rfind(end)])

Also Gives #

I am a test paragraph
Answered By: Bhargav
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.