1

This is what I have been trying so far. Basically, I want to split the string but keep the separator. My regex knowledge is very limited but I've been trying using a forward lookup to match the expression. Whenever I try to introduce \*1 into the string split, it goes badly so I'm not sure what to do and if this is possible.

var tests = new List<string> 
{
    "*foo**bar*!bob",
    "*foo*!42",
    "!foo*bar*"
};

foreach (var expression in tests)
{
    var strings = Regex.Split(expression, @"(?=[!])");
    Console.WriteLine(String.Join(Environment.NewLine, strings));
}

1st line:

*foo**bar*
!bob

2nd Line (this is working as expected)

*foo*
!42

3rd line

{EMPTY LINE}
!foo*bar*

But I'm trying to get back is:

1st line

*foo*
*bar*
!bob

2nd line - As Above (this is correct)

3rd line

!foo
*bar*
webnoob
  • 15,747
  • 13
  • 83
  • 165

1 Answers1

2

Try this...

var tests = new List<string> 
{
    "*foo**bar*!bob",
    "*foo*!42",
    "!foo*bar*"
};

foreach (var expression in tests)
{
    var strings = Regex.Split(expression, @"(?=[!])|(\*[^\*]+\*)").Where(exp => !String.IsNullOrEmpty(exp));
    Console.WriteLine(String.Join(Environment.NewLine, strings));
}

Results:

*foo*
*bar*
!bob
*foo*
!42
!foo
*bar*
Shar1er80
  • 9,001
  • 2
  • 20
  • 29
  • Legend! Thanks very much, works perfectly. I wasn't too far off in my second test locally so I'll take some satisfaction in that ;) I'll mark it as the answer when I'm allow. Thanks again for your time. – webnoob Jun 24 '15 at 19:46