I am trying extract some information from the below given string
>>> st = '''
... <!-- info mp3 here -->
... 192 kbps<br />2:41<br />3.71 mb </div>
... <!-- info mp3 here -->
... 3.49 mb </div>
... <!-- info mp3 here -->
... 128 kbps<br />3:31<br />3.3 mb </div>
... '''
>>>
Now when I use the below regex my output is
>>> p = re.findall(r'<!-- info mp3 here -->\s+(.*?)<br />(.*?)<br />(.*?)\s+</div>',st)
>>> p
[('192 kbps', '2:41', '3.71 mb'), ('128 kbps', '3:31', '3.3 mb')]
but my required output is
[('192 kbps', '2:41', '3.71 mb'),(None,None,'3.49mb'), ('128 kbps', '3:31', '3.3 mb')]
So, my question is how do I change my above regex to match all the conditions.I believe my current regex is strictly dependent on <br /> tags so how do I make it conditional on that.
I know I should not be using regex to parse html but currently this is the most appropriate way for me.
The following will work, though I wonder if there’s not a more elegant solution. You can certainly combine the list comprehensions into one line, but I think that makes the code less clear overall. At least this way you’ll be able to follow what you did three months from now…
And, depending on the variability in your string, you may want to write a more generic cleaning function that strips, cases, whatever, and map it to each item you pull out.