2011-04-02 82 views
2

这将是一个快速的方法来提取一个HTML表格标题属性的值:正则表达式来提取属性值

... 
<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> 
... 

所以它会返回Proclo,普洛克洛,托勒密,毕达哥拉斯,....在每行的字符串中。我正在使用StreamReader读取文件。我正在使用C#。

谢谢。

+0

你有什么形式的HTML表? (ASP控件,字符串,流,XmlReader,DOM?) – sehe 2011-04-02 21:46:49

+0

\ *叹息\ * ... http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-标签/ 1732454#1732454为(1/epsilon)次。 – delnan 2011-04-02 21:46:50

+0

@ delnan:优点。然而,链接到的帖子似乎已经损坏?它无法在我的浏览器中正确显示 – sehe 2011-04-02 21:47:49

回答

14

这个C#正则表达式会发现所有标题值的情况:

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

的C#代码是这样的:

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

正则表达式使用正回顾后找到位置,其中title VALU e开始。然后它将所有内容匹配到最后的双引号。

+0

它只适用于我删除while循环。谢谢 ! – al1 2011-04-02 22:01:57

+0

好的,我会尽量简化它 – 2011-04-02 22:06:19

5

使用下面

title="(.[^"]+)" 

,然后正则表达式使用通过匹配的元素浏览。

编辑:我已经修改了正则表达式来涵盖@StaffanNöteberg在评论规定

+0

对于这些示例来说没关系,这可能就足够了。但不会与'

  • Proclo
  • '或'
  • Proclus
  • '一起使用。 – 2011-04-02 22:00:12

    +0

    @StaffanNöteberg好点,现在它也应该涵盖你的例子。 – 2011-04-02 22:15:19