Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx get tr tags

I have the string:

'
<tr id="sdf"></tr>
<td>
  <div>asdf</div>
  asdf
</td>
<tr id="sdfdf">
  <td>
    <div>asdf</div>
    asdf
  </td>
</tr>
<tr id="sdf"></tr>
<tr id="ssdfdf">
  <td>
    <div>asdf</div>
    asdf
  </td>
</tr>
'

and I'd like to save tr tags into an array using RegExp.

like image 511
Alexander Avatar asked Oct 17 '25 15:10

Alexander


1 Answers

As long as <tr> tags are never nested, you could try this:

result = subject.match(/<tr[\s\S]*?<\/tr>/g);

This gets you an array of all <tr> tags and their contents.

[\s\S] is the JavaScript way of saying "any character, including newlines", and *? asks for zero or more repetitions of that, trying to use as few as possible to avoid matching across multiple tags at once.

This blows up as soon as <tr> tags are nested, though, which is one of the reasons why regexes are not the best tool for parsing markup languages (to put it mildly). You will get more reliable results by parsing the DOM.

like image 73
Tim Pietzcker Avatar answered Oct 20 '25 04:10

Tim Pietzcker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!