0

I have the following html contained in a string.

<tr>
   <td>Hello</td>
</tr>
<tr>
   <td>World</td>
</tr>
<tr>
   <td>lets all smile</td>
</tr>

I would like to use RegEx to find the <tr></tr> that contains the text "World". The difficulty is that there might be other <td> around the one that contains the search text. So we need to be able to search for the <tr> and </tr> nearest to the search text with any text between the <tr> and the search text.

The result of the match would be.

<tr>
   <td>World</td>
</tr>

I'm using vb.net by the way.

Could anyone help at all?

Thanks

Richard

2
  • you could have easily typed html (instead of &gt; &lt;) by selecting and formatting it with ctrl-k Commented Dec 8, 2009 at 10:24
  • Read this blog post from our benevolent leader: codinghorror.com/blog/archives/001311.html Commented Dec 8, 2009 at 15:47

1 Answer 1

6

First of all, it should be pointed out that you want to use the HTML Agility Pack, and not regex, for this kind of things.

But other than that, a pattern could look like:

(<tr>.*?World.*?</tr>)

It's a rather lousy pattern, but then again, use the agility pack.

Sign up to request clarification or add additional context in comments.

9 Comments

wouldn't this match the first 6 lines - from first <tr> to the </tr> after World?
No, the non-greedy operators ? will make sure the whitespace between <tr> and World is kept as small as possible, without breaking the match
Tested on Expresso and got this. <tr><td>Hello</td></tr><tr><td>World</td></tr>
That is not how non-greediness work. Non greediness is responsible for not matching the whole string (including the last </tr>) - after all the whole string starts with <tr> and ends with </tr> - but due to the .*? at the end of regex, it matches the first </tr>
cool, i managed to reproduce the same actually. so the pattern could be rewritten (something quick and dirty would be (<tr>[^<]*<td>World.*?</tr>)), but more importantly, my main point in my reply was for expressions such as these not to be used
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.