2012-03-05 216 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

相关问题