0

I've been trying to do this for some time now, but my Regex skills are pretty bad. I have this text

<td class="red">
    One
</td>
<td>
    Two
</td> 

And I want to get the value of "Two". I've tried multiple things like

<td>\n(.*)\n</td>
<td class=\"red\">\nOne\n</td>\n<td>\n(.*)\n</td>

And this is my C# source

foreach (Match m in Regex.Matches(src, pattern, RegexOptions.IgnorePatternWhitespace))
{
    MessageBox.Show(m.Groups[1].Value);
}

I tried changing the RegexOptions with no luck. If anyone could help me it'd be greatly appreciated. Thank you

3
  • Use XElement class, it is much easier. Commented Jun 25, 2014 at 13:22
  • use HTML agility pack it would be much simpler rather then now Commented Jun 25, 2014 at 13:24
  • XElement.Parse("<Your xml fragment">).Elements("td").Last().Value Commented Jun 25, 2014 at 13:26

3 Answers 3

1

Why not simply :

string expression = @"\<td\>[\s]*[A-Za-z]*[\s]*\</td\>";

And if you want to name your group

string expression = @"\<td\>[\s]*(?<groupName>([A-Za-z]*))[\s]*\</td\>";
Sign up to request clarification or add additional context in comments.

Comments

0

Use the s (DotAll) modifier forcing the dot . to match newline sequences as well.

foreach (Match m in Regex.Matches(src, @"(?s)<td>\s*(.*?)\s*</td>"))
         MessageBox.Show(m.Groups[1].Value);

Note: Follow .* with ? for a non-greedy match here.

Comments

0

Enable dotall(s) modifier to make . to match a newline character.

(?<=<td>)\s*(\w*)\s*(?=<\/td>)

DEMO

And your code would be,

Regex rgx = new Regex(@"(?s)(?<=<td>)\s*(\w*)\s*(?=<\/td>)");
foreach (Match m in rgx.Matches(input))
Console.WriteLine(m.Groups[1].Value);

Comments

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.