I am trying to match all <tr> elements that contain the word “Source”, but when the other attributes (colspan/width/height, contained <td>s and their attributes, etc.) are unknown. (I know this can be done with a javascript/jQuery selector, but I am just processing the HTML for a non-javascript context.)
Example of target:
<tr>
<td>Don't affect this</td>
</tr>
<tr>
<td colspan="3" width="288" height="57"><strong>Sources:</strong> Author</td>
</tr>
(This is what I want to change it to:)
<tr>
<td>Don't affect this</td>
</tr>
<tr class="source">
<td colspan="3" width="288" height="57"><strong>Sources:</strong> Author</td>
</tr>
Here are regex patterns I have tried that haven’t worked:
/<tr>((?:.*?)Source(?:s?):(?:.*?))<\/tr>/gmi,
No matches.
/<tr>((?:[\s\S]*?)Source(?:s?):(?:[\s\S]*?))<\/tr>/gmi,
Matches the first tr, but not the second.
I think there’s regex principle I may be failing to grasp here, about greediness or something related. Any suggestions?
Are you sure you can’t use jQuery for this? 😛 But seriously, this will be easier to grasp if I put it in terms of Friedl’s “unrolled loop” idiom:
opening:
<tr[^>]*>– the opening<tr>tagnormal:
(?:(?!<|source)[\s\S])*– zero or more of any characters, with the lookahead to make sure each time that the character is not the beginning of a tag or the word “source”special:
<(?!\/?tr)[^>]*>– any tag except another opening<tr>or a closing</tr>. By consuming a complete tag, we avoid false positives on the word “source” in the name or value of an attribute.closing:
source– The only other thing it could possibly encounter here is a<tr>or</tr>tag, which would indicate a failed match for our purposes. Finding “source” before one of those tags is how we know we’ve found a match. (The rest of the regex,[\s\S]*?<\/tr>, merely consumes the remainder of the tag so you can retrieve it viagroup[0].)A
<tr>there isn’t necessarily invalid, of course; it could be the beginning of a nested TR element, presumably within a nested TABLE element. If that TR contains the word “source”, the regex will match it on a separate match attempt. It will match only the innermost, complete TR tag with the word “source” in it.As usual when using regexes on HTML, I’m making several simplifying assumptions involving well-formedness, SGML comments, CDATA sections, etc., etc. Caveat emptor.