2014-09-22 50 views
2

Ich在多行文本中顯示c#中的正則表達式替換函數時出現問題。在這個文本中,我有不同的行有時與特殊字符(例如:&和& &)在一開始行必須轉換例如。 HTML。這是作爲一個降價的轉換類似...Regex.replace將不會替換多行文本行以開始字符到html塊

一個例子如下文字:

This is a normal demo text. 
&Here an other demo text. 
And one more demo text. 
&&Here will continue this text. 
Bla bla blaaa... 

文本應替換爲在與開始和結束HTML標記文本後:

This is a normal demo text. 
<b>Here an other demo text.</b> 
And one more demo text. 
<em>Here will continue this text...</em> 
Bla bla blaaa... 

對於替換&和& &我創建了以下c#代碼:

private string StartConvert(str text) 
{ 
text = Regex.Replace(text, "^[&]{1}((?![&]).+)$", "<b>$1</b>", RegexOptions.Multiline); 
text = Regex.Replace(text, "^[&]{2}((?![&]).+)$", "<em>$1</em>", RegexOptions.Multiline); 
} 

運行,我會得到錯誤以下後:

This is a normal demo text. 
</b>ere an other demo text. 
And one more demo text. 
</em>ere will continue this text... 
Bla bla blaaa... 

爲什麼這工作不正常,爲什麼我行的前面拿到,只有關閉標籤。如果它是一個單獨的行,它可以正常工作,但不是多行。

感謝您的幫助

+0

如何分配的輸入? – 2014-09-22 07:08:55

+0

我也測試了這個,Regex在正則表達式製造商中工作正常,但是當涉及到C#時,它跳過H – Charlie 2014-09-22 07:22:52

+0

您的代碼適用於我http://ideone.com/XhQzoR – 2014-09-22 07:37:20

回答

0

我假設你的文件是Windows EOF編碼:\r\n

表達式:"^[&]{1}((?![&]).+)$"將匹配&Here an other demo text.\r\n

後面的參考((?![&]).+)將是Here an other demo text.\r

有了這個替換字符串:<b>Here an other demo text.\r</b>

<b>Here an other demo text.\r 
^___________________________| 

CR \r光標返回到該行的開頭。

</b>ere an other demo text.\r 
|__^ 

重寫<b>H</b>

0

這不是解決辦法,但我可以告訴你,這個問題是不是在正則表達式,問題出在打印文本。我看到了結果字符串是完全正常 所以我做了這樣的事情來檢查它

 string[] strings = text.Split(' '); 

     foreach (var s in xa) 
     { 
      Console.WriteLine(s); 

     } 

你可以檢查字符串,而調試,這是好的?