12

What would be a quick way to extract the value of the title attributes for an HTML table:

...
<li><a href="/wiki/Proclo" title="Proclo">Proclo</a></li>
<li><a href="/wiki/Proclus" title="Proclus">Proclus</a></li>
<li><a href="/wiki/Ptolemy" title="Ptolemy">Ptolemy</a></li>
<li><a href="/wiki/Pythagoras" title="Pythagoras">Pythagoras</a></li></ul><h3>S</h3>
...

so it would return Proclo, Proclus, Ptolemy, Pythagoras,.... in strings for each line. I'm reading the file using a StreamReader. I'm using C#.

Thank you.

al1
  • 123
  • 1
  • 1
  • 5
  • And in what form do you have your html table? (ASP controls, strings, stream, XmlReader, DOM?) – sehe Apr 02 '11 at 21:46
  • \*Sigh\*... http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 for the (1/epsilon)th time. –  Apr 02 '11 at 21:46
  • @delnan: excellent point. However, the post linked to seems to have been corrupted? It isn't showing correctly in my browser – sehe Apr 02 '11 at 21:47
  • @sehe: That post has numerous obscure unicode characters sprinkled in for effects, laughs and as a reference to [some weird meme](http://knowyourmeme.com/memes/zalgo). It's intended to look broken. –  Apr 02 '11 at 21:51

2 Answers2

38

This C# regex will find all title values:

(?<=\btitle=")[^"]*

The C# code is like this:

Regex regex = new Regex(@"(?<=\btitle="")[^""]*");
Match match = regex.Match(input);
string title = match.Value;

The regex uses positive lookbehind to find the position where the title value starts. It then matches everything up to the ending double quote.

Staffan Nöteberg
  • 4,095
  • 1
  • 19
  • 17
12

Use the regexp below

title="([^"]+)"

and then use Groups to browse through matched elements.

EDIT: I have modified the regexp to cover the examples provided in comment by @Staffan Nöteberg

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
MPękalski
  • 6,873
  • 4
  • 26
  • 36
  • @Staffan Nöteberg Good point, now it should also cover your examples. – MPękalski Apr 02 '11 at 22:15