C# split large string with Regex.Split. Must keep delimiters

Viewed 149

I'm trying to split a wall of text into an array using regex and it's working fairly well but I don't want it to erase the delimiters I'm using. I've looked into look ahead function but I cant get it to work correctly or at all.

I have the following Regex which splits at the following combinations "Artículo #.", "Artículo ##.", 1), 2) etc and a), b), c) and at the word "Párrafo".

var result = Regex.Split(text, @"(Artículo)\s[0-9](.)|(Artículo)\s[0-9][0-9](.)|[a-z](\))|[1-9](\))|[1-9][0-9](\))|(Párrafo)", RegexOptions.None);

I need to keep the keywords which I've used to split. For example I have the following text

Artículo 1. This is a test that includes : 1) Sample text 2) Sample text

Crrently I'm getting:

 This is a test that includes :
 Sample text
 Sample text

What I need:

Artículo 1. This is a test that includes :
1) Sample text
2) Sample text

I feel I'm getting close but any help would be great.

1 Answers

You can use

var text = "Artículo 1. This is a test that includes : 1) Sample text 2) Sample text";
var result = Regex.Split(text, @"(?!^)\s+(?=\bArtículo\s+[0-9]+\.|[a-z]\)|[1-9]\d?\)|\bPárrafo\b)", RegexOptions.None);
Console.WriteLine(string.Join("\n", result));
// => Artículo 1. This is a test that includes :
// => 1) Sample text
// => 2) Sample text

See the C# demo and the regex demo.

The regex is

(?!^)\s+(?=\bArtículo\s+[0-9]+\.|[a-z]\)|[1-9]\d?\)|\bPárrafo\b)

It matches

  • (?!^) - a location other than start of string
  • \s+ - 1+ whitespaces (if you use \s*, you will need to add .Where(x => !string.IsNullOrEmpty(x)) after the Regex.Split call)
  • (?=\bArtículo\s+[0-9]+\.|[a-z]\)|[1-9]\d?\)|\bPárrafo\b) - a location that is immediately followed with
    • \bArtículo\s+[0-9]+\.| - whole word Artículo, 1+ whitespaces, 1+ ASCII digits, and a ., or
    • [a-z]\)| - a lowercase ASCII letter and ), or
    • [1-9]\d?\)| - a non-zero digit, then an optional digit and a ), or
    • \bPárrafo\b - a whole word Párrafo.
Related