2012-04-04 58 views
1

我想製作一個函數,可以從字符串中斷行。使用正則表達式替換

如: 「1」 - > 「\ N1。」

,所以我可以這樣寫

string Input = "1. First option"; 
Input += "2. Second option"; 
Input += "3. Third option"; 

Output = WriteMenu(Input); 

代碼,並得到這樣

"1. First option 
\n2. Second option 
\n3. Third option" 

字符串該模式將始終爲[數字] [點] [空格]。 如果第一個選項帶有新行,這不是問題。

+0

所以僅僅是明確的(因爲它似乎目前的答案都忽略了這):你**不需要''''前面​​的CRLF? – slugster 2012-04-04 00:15:42

回答

4

給這傢伙一個鏡頭

Input = Regex.Replace(Input, @"(?<!^)(\d+\.)", "\n$1") 
+0

完美的作品!謝謝 :) – 2012-04-04 01:14:18

2
Regex rgx = new Regex("(\\d+\\.\\s)"); 
String replaced = rgx.Replace(Input, Environment.NewLine + "$1"); 
1

短一點表情像這樣的工作太:

Regex.Replace(Input, @"(?!^)\d+\.", "\n$0")