By default I would reach for String.Split
unless you have some complicated requirements that a regex would enable you to navigate around. Of course, as others have mentioned, profile it for your needs. Be sure to profile with and without RegexOptions.Compiled
too and understand how it works. Look at To Compile or Not To Compile, How does RegexOptions.Compiled work?, and search for other articles on the topic.
One benefit of String.Split
is its StringSplitOptions.RemoveEmptyEntries
that removes empty results for cases where no data exists between delimiters. A regex pattern of the same split string/char would have excess empty entries. It's minor and can be handled by a simple LINQ query to filter out String.Empty
results.
That said, a regex makes it extremely easy to include the delimiter if you have a need to do so. This is achieved by adding parentheses ()
around the pattern to make it a capturing group. For example:
string input = "a|b|c|d|e|f";
foreach (var s in Regex.Split(input, @"\|"))
Console.WriteLine(s);
Console.WriteLine("Include delimiter...");
// notice () around pattern
foreach (var s in Regex.Split(input, @"(\|)"))
Console.WriteLine(s);
You might find this question helpful as well: How do I split a string by strings and include the delimiters using .NET?