通过c#中的正则表达式提取字符串

时间:2012-09-26 13:37:34

标签: c# regex string

我有一些html文件,代码如下:

 <div style="border: 0px red solid; width: 633px; position: relative; margin: 0px;
                                                                float: right">
                                                                <font style="font-size: 8pt; color: Navy; font-weight: Bold;">Unit Name: </font>My Unit Name&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <font style="font-size: 8pt; color: Navy; font-weight: Bold;">
                                                                    Manager: </font>My Manager Name&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <font style="font-size: 8pt;
                                                                        color: Navy; font-weight: Bold;">Category: </font>My Category
                                                            </div>
                                                            <div style="border: 0px red solid; width: 122px; position: relative; margin: 0px;
                                                                padding: 0px;">
                                                                <button name="sSdewfwo87kjLKH7624QAZMLLPIdyt75576rtffTfdef22de" style="font-family: Tahoma;"
                                                                    onclick="OpenMyWin2(1,843442,8445,'bf61fd588f00cbe7a37dab20c62e1c63')">
                                                                    More Info</button></div>

我想在分类前面提取信息:&amp;经理:&amp;单位名称:如何使用RegularExpression从大型html文件中提取这些内容。这些文件可能有100个相似的项目。

3 个答案:

答案 0 :(得分:0)

我建议您考虑使用该工具: http://htmlagilitypack.codeplex.com/

它可以轻松解析您想要的任何HTML。

答案 1 :(得分:0)

使用正则表达式解析HTML 代码是一个“好主意”,但是如果你想使用正则表达式,请使用模式:

>\s*Unit Name:[^>]*>([^<]+).*?>\s*Manager:[^>]*>([^<]+).*?>\s*Category:[^>]*>([^<]+)

可以缩减为

>\s*(?:Unit Name|Manager|Category):[^>]*>([^<]+)

要修剪&nbsp;个尾部,请使用([^<]+)替换正则表达式中的(\w+)

答案 2 :(得分:0)

也许这可以帮到你。这使用 Lookahead and Lookbehind Zero-Width Assertions.

 (?<=(Category:|Manager:|Unit Name:) (</font>)?).*?(?=(&|<))

RegexBuddy ScreenShot

enter image description here