C# how to separate a string by numbering (1. 2. ...)

Viewed 259

I have this string "1: This 2: Is 3: A 4: Test" and would like to split it based on the numbering, like this:

"1: This"
"2: Is"
"3: A"
"4: Test"

I think this should be possible with a regular expression, but unfortunately I don't understand much about it.

This: string[] result = Regex.Split(input, @"\D+"); just splits the numbers without the colon and the content behind it.

3 Answers

You can use

string[] result = Regex.Split(text, @"(?!^)(?=(?<!\d)\d+:)")

See this regex demo. Note that the (?<!\d) negative lookbehind is necessary when you have bullet point with two or more digits. Details:

  • (?!^) - not at the start of string
  • (?=(?<!\d)\d+:) - the position that is immediately followed with one or more digits (not preceded with any digit) and a : char.

If you use a capture group () like this:

string[] result = Regex.Split(str, @"(\d+:)");

the captured values will be added to the array too. Then all that is left to do is to merge every first value with every second value (we skip index 0 as it is empty):

List<string> values = new();
for (int i = 1; i < result.Length; i += 2)
{
    values.Add(result[i] + result[i + 1]); 
}

There are probably cleaner ways to do this, but this works.

Using \D+ matches 1 or more non digits, and will therefore match : This to split on.

Instead of using split, you can also match the parts:

\b[0-9]+:.*?(?=\b[0-9]+:|$)

The pattern matches:

  • \b A word boundary to prevent a partial word match
  • [0-9]+: Match 1+ digits and :
  • .*? Match as least as possible characters
  • (?=\b[0-9]+:|$) Positive lookahead, assert either 1+ digits and : or the end of the string to the right

.NET regex demo

Example in C#:

string str = "1: This 2: Is 3: A 4: Test";
string pattern = @"\b[0-9]+:.*?(?=\b[0-9]+:|$)";

MatchCollection matchList = Regex.Matches(str, pattern);
string[] result = matchList.Cast<Match>().Select(match => match.Value).ToArray();

Array.ForEach(result, Console.WriteLine);

Output

1: This 
2: Is 
3: A 
4: Test
Related