简体   繁体   中英

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

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.

import re

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

result = re.sub(r"<p .*=.*>\$\$.*?</?p>", "1", s)
result = re.sub(r"<p.*>\$\$.*?</?p>", "1", result) 

print(result)

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM