Skip to content
Advertisement

How to parse paragraph in html using regex

I need to write a regex to parse $$ sign between paragraphs in an HTML page I tried

s = "<p>adsadfsaaadsadsaExample String</p><p>$$</p>"
replaced = re.sub('<p>$$</p>', '1',s)
print (replaced)

But I need to apply the same even there are some styles exists in paragraph,

Expected Input:

<p>i have</p> <p style="text-align:justify">$$</p>
<p> asdas jas dafad</p>
<p>$$<p>
<p>asdasd</p>
<p><span>$$</span></p>

Expected Output:

<p>i have</p> 1 
<p> asdas jas dafad</p>
1
<p>asdasd</p>
1

please help

Advertisement

Answer

import re

pattern = r'<p.*?>.*?</p>'
html_str = '<p>i have</p> <p style="text-align:justify">$$</p><p> asdas jas dafad</p><p>$$</p><p>asdasd</p><p><span>$$</span></p>'
new_html_str = re.sub(pattern, lambda match: "1" if '$$' in match.group() else match.group(),s)
print(new_html_str)

prints - '<p>i have</p> 1<p> asdas jas dafad</p>1<p>asdasd</p>1'

my answer is completely based on your approach, for a better solution, I suggest to parse the html and process.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement