Nikhil Agrawal
Nikhil Agrawal

Reputation: 48558

Regex to split a string using a character preceded by a particular character

I have a string which i want to split using a character preceded by a particular character

Foo:xxxxxxxxx:Bar:xxxxxxxx:FooBar:xxxxxxx

I want to split it using colon : coming after x.

I tried x: but it is removing last x.

I know that i can use this regex and then append x in each splitted string but is there a way to split this string using regex so that last x is also there.

Upvotes: 0

Views: 875

Answers (4)

Ria
Ria

Reputation: 10367

Try lookbehind assertion:

(?<=x):

and your code like this:

var result = Regex.Split(inputString, "(?<=x):");

explain:

(?<= subexpression)
Zero-width positive lookbehind assertion.

for sample: if you apply (?<=19)\d{2} Regex on

1851 1999 1950 1905 2003 the result is

99, 50, 05

Upvotes: 3

sbutler
sbutler

Reputation: 637

Zero-width positive lookbehind assertion.

(?<=x):

Upvotes: 2

Alex Kalicki
Alex Kalicki

Reputation: 1533

Use positive lookbehind in C#'s Regex.Split method:

string[] substrings = Regex.Split("Foo:xxxxxxxxx:Bar:xxxxxxxx:FooBar:xxxxxxx", "(?<=x):");

Upvotes: 1

Eugene Ryabtsev
Eugene Ryabtsev

Reputation: 2301

var list = Regex.Split("Foo:xxxxxxxxx:Bar:xxxxxxxx:FooBar:xxxxxxx", "(?<=x):");

It uses positive lookbehind, as per sbutler's.

Upvotes: 1

Related Questions