2013-03-03 52 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如果堅持比使用字符串選項