How to split a string on multiple single‑character delimiters (and keep them) in C#

1 Answer

0 votes
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

class SplitKeepDelimsProgram
{
    public static List<string> SplitKeepDelims(string s, string delimiters) {
        var result = new List<string>();

        // Build regex: e.g. ",;|" → "([,;|])"
        string pattern = "([" + Regex.Escape(delimiters) + "])";
        var re = new Regex(pattern);

        int lastEnd = 0;

        foreach (Match m in re.Matches(s)) {
            // Add text before delimiter
            if (m.Index > lastEnd) {
                result.Add(s.Substring(lastEnd, m.Index - lastEnd));
            }

            // Add the delimiter itself
            result.Add(m.Value);

            lastEnd = m.Index + m.Length;
        }

        // Add remaining text after last delimiter
        if (lastEnd < s.Length) {
            result.Add(s.Substring(lastEnd));
        }

        return result;
    }

    static void Main()
    {
        string input = "aa,bbb;cccc|ddddd";
        var parts = SplitKeepDelims(input, ",;|");

        foreach (var p in parts)
        {
            Console.Write("[" + p + "] ");
        }
    }
}


/*
run:

[aa] [,] [bbb] [;] [cccc] [|] [ddddd] 

*/

 



answered Mar 9 by avibootz

Related questions

...