-2

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

RatheeshTS
  • 411
  • 3
  • 15
  • 1
    don't do it! use html.parser instead. if you still insist, read https://blog.codinghorror.com/parsing-html-the-cthulhu-way/. – Sixtyfive Jan 24 '21 at 08:11

2 Answers2

1
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.

Mahesh Anakali
  • 344
  • 1
  • 8
  • 1
    Thanks bro, This is just a potion of the code, My intention is not to parse entire code, Just add some extra tags and process, so I followd this approch – RatheeshTS Jan 25 '21 at 10:05
-2
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
Cosmos
  • 372
  • 2
  • 6