2013-03-03 40 views
1

我有一个关于在C#中操作字符串的问题。有条件地替换字符串部分

说我有一个字符串:

"Today I ate a <a href="link here "> chocolate </a> at the <a href=\"another link here"> supermarket</a>. It was a brand of <a href=\"3rd link">Contoso</a> 

我想使它:

"Today I ate a chocolate at the supermarket. It was a brand of Contoso. 

我可以删除它的</a>的一部分,但我不确定如何去除一切和任何<a href>之间

我该如何去做这件事?

在此先感谢!

+1

Look [here](http://stackoverflow.com/questions/787932/using-c-sharp-regular-expressions-to-remove-html-tags) – tttony 2013-03-03 02:09:00

回答

0

Regex可能是最好的选择,但是如果你不想使用Regex,按照你想要的方式解析字符串将会非常麻烦。

一个想法可能是由</a>分割字符串,然后抢在西尔的<a侧和>

var result = new string (input.Split(new string[] { "</a>" }, StringSplitOptions.RemoveEmptyEntries) 
    .SelectMany(s => s.Where((c, i) => i < s.IndexOf("<a") || i > s.IndexOf(">"))).ToArray()); 

所有字符所以我会用它为你工作作为其轻松很多的Regex如果坚持比使用字符串选项