日期:2014-05-18  浏览次数:20957 次

正則表達式的困擾,請幫忙!!
現在   有   一個     html原始檔     我需要把其中的所有   html標記替換   成   空格   但是   要保留   </td>   這個標記   就是說 <html> </html>   <body> </body> <tr> </tr> <td>   之類的全部不要     但是   </td>   這個標記   一個   都不能替換     這個   正則表達式   應該怎樣寫啊     請各位   熱心的   朋友   看清楚     我的   問題     然后   不吝賜教     謝謝

------解决方案--------------------
把 <td> </td> 全部捕获,放入Matchs中,然后用一个foreach来把捕获组集合中所有的值全部加入一个string。
string content = " "; // 你的文件字符串
Regex htmlRegex = new Regex(@ " <td[^> ]*> .*? </td> ", RegexOptions.IgnoreCase | RegexOptions.Compiled);
MatchCollection mc = htmlRegex.Matches(content);
string result = " ";
foreach (Match m in mc)
{
result += m.Value+ "\n ";
}
Console.WriteLine(result);
Console.ReadKey();
------解决方案--------------------
上面的表达式适合简单的嵌套,对复杂的嵌套无能为力。

简单嵌套
<table>
<tr>
<td width= "50 "> simple </td>
<td> way </td>
</tr>
<tr>
<td> good </td>
<td> </td>
</tr>
</table>

复杂多层嵌套
<table>
<tr>
<td> <table>
<tr>
<td> hard </td>
</tr>
</table>
</td>
</tr>
</table>
------解决方案--------------------
楼主试下下面的程序能达到你要的要求吗?MyString就是要替换的字符串
string MyString = " <html> aaa <p> </td> <html> aaa <p> </td> <hhhhh a a > 2324 ";
Regex RegexMark = new Regex(@ " <[^( <|> )]+> ");
int x = RegexMark.Matches(MyString).Count;
int count = 0;
for (int n = 0; n < x; n++)
{
try
{
if (RegexMark.Matches(MyString)[count].ToString() == " </td> ")
{
count++;
continue;
}
}
catch
{
break;
}
string Space = " ";
for (int y = 0; y < Convert.ToString(RegexMark.Matches(MyString)[count]).Length; y++)
Space = Space + " ";
MyString = MyString.Replace(RegexMark.Matches(MyString)[count].ToString(), Space);
}
------解决方案--------------------
起来后洗衣服去了^o^

楼主这个要求有点特别,呵呵,一般是单独保留 <br> 还有意义,保留 </td> 想不通是做什么,不过这个很简单了,是各位把它想复杂了

string yourStr = ................;
string result = Regex.Replace(yourStr, @ " <(?!/td> )[^> ]*> ", " ", RegexOptions.IgnoreCase);

另外楼主说把
html標記替換 成 空格
是替换成空格还是替换为空,这里替换为空了,如果是替换为空格,楼主自己加上吧