Regular expression to match HTML table row <tr>

Post Reply
tong
Site Admin
Posts: 2387
Joined: Fri 01 May 2009 8:55 pm

Regular expression to match HTML table row <tr>

Post by tong »

Code: Select all

<tr>
    <td> ... </td>
    <td> ... </td>
    <td>SUBSTRING I HAVE TO MATCH HERE</td>
    <td> ... </td>
    <td> ... </td>
</tr>
Here is a regex makeshift solution.
To ensure SUBSTRING occurs inside a row, you need to use this:

Code: Select all

<tr>((?!</tr>).)+?SUBSTRING.+?</tr>
(?!...) is a negative lookahead. The lookahead makes sure that never go past the end of one table row, just to find SUBSTRING in the next one. It does this by asserting for every single character in our +? repetition, that it does not mark the beginning of </tr>.

To ensure that SUBSTRING does not occur inside the row, we can simply put SUBSTRING into that negative lookahead we already have:

Code: Select all

<tr>((?!SUBSTRING).)+?</tr>
*? Match 0 or more times, not greedily
+? Match 1 or more times, not greedily
?? Match 0 or 1 time, not greedily
tong
Site Admin
Posts: 2387
Joined: Fri 01 May 2009 8:55 pm

Re: Regular expression to match HTML table row <tr>

Post by tong »

Code: Select all

HTML = HTML.replace(/<tr ((?!<\/tr>)(.|\n))+?ShungOu(.|\n)+?<\/tr>/ig, "");
tong
Site Admin
Posts: 2387
Joined: Fri 01 May 2009 8:55 pm

Re: Regular expression to match HTML table row <tr>

Post by tong »

Code: Select all

HTML = HTML.replace(/<a href="details.php\?id=(\d+)&hit=1">/ig, '<a href="details.php?id=$1" target=_blank>');
เราสามารถใช้ '.....'
$1 แทน match group

Code: Select all

HTML = HTML.replace(/<option value="9"( selected="selected")?>.<\/option>/i, '<option value="9" $1>XXX</option>');
( selected="selected")? แทน match group 0 หรือ 1 ครั้ง
Post Reply