William Walseth
William Walseth

Reputation: 2923

Regular Expression to Split String

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?

Upvotes: 1

Views: 196

Answers (2)

ruakh
ruakh

Reputation: 183574

That's because you're splitting on (for example) ,2 — the 2 is considered part of the separator, just like the comma. To fix this, you can use a lookahead assertion:

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

meaning "a comma, provided the comma is followed immediately by a nonzero digit".

Upvotes: 1

Qtax
Qtax

Reputation: 33928

You can use a lookahead (?=...), like in this expression:

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

Remove the \s* if you don't want to allow spaces between the , and the N..

Upvotes: 3

Related Questions