I’m trying to write a regular expression to split the following string
"17. Entertainment costs,16. Employee morale, health, and welfare costs,3. Test"
Into
17. Entertainment costs
16. Employee morale, health, and welfare costs
3. Test
Note the commas in the second string.
I’m trying
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 );
}
}
But the #’s don’t come through
1.One
.Test,one,two,three
.Did it work?
That’s because you’re splitting on (for example)
,2— the2is considered part of the separator, just like the comma. To fix this, you can use a lookahead assertion:meaning “a comma, provided the comma is followed immediately by a nonzero digit”.