2012-03-05 214 views
1

我想寫一個正則表達式來分割以下字符串正則表達式分割字符串

"17. Entertainment costs,16. Employee morale, health, and welfare costs,3. Test" 

進入

17. Entertainment costs 
16. Employee morale, health, and welfare costs 
3. Test 

注意逗號第二的字符串中。

我想

static void Main(string[] args) { 
     Regex regex = new Regex(",[1-9]"); 
     string strSplit = "1.One,2.Test,one,two,three,3.Did it work?"; 
     string[] aCategories = regex.Split(strSplit); 
     foreach (string strCat in aCategories) { 
      System.Console.WriteLine(strCat); 
     } 
    } 

但#的不來通過

1.One 
.Test,one,two,three 
.Did it work? 
+0

通過split,「[1-9]」,你永遠不會得到數組aCategories中的數字。也許試着找到「,[1-9]」的索引,然後用它來保持子串,從而保持數字? – Justmaker 2012-03-05 14:36:53

回答

1

這是因爲你分裂(例如),22被認爲是分隔符的一部分,就像逗號。爲了解決這個問題,你可以使用一個lookahead assertion

 Regex regex = new Regex(",(?=[1-9])"); 

意思是「一個逗號,所提供的逗號是一個非零數字緊跟」。

+0

謝謝大家!點到處。 – 2012-03-05 14:48:38

+0

@WilliamWalseth:不客氣! – ruakh 2012-03-05 14:50:38

3

您可以在此表達式中使用a lookahead(?=...),如:

@",(?=\s*\d+\.)" 

刪除\s*如果您不想允許之間的空格和N.

+0

我不認爲數字前有空格。 – 2012-03-05 14:38:23

相關問題