3

i have for exemple this string "abc({".
now, i want to split it by the "(" delimiter, and i know i can use String.split for that.
but is there a way i can split if by this symbol but not loss it? like if i used split i would have gotten this string[] = { "abc" , "{" } and i want { "abc" , "(" , "{" }.
also is there a way to do this with multiple delimiters?

vertigo
  • 125
  • 8

1 Answers1

2

Use Regex.Split with a pattern enclosed with a capturing group.

If capturing parentheses are used in a Regex.Split expression, any captured text is included in the resulting string array.

See the C# demo:

var s = "abc({";
var results = Regex.Split(s, @"(\()")
    .Where(m=>!string.IsNullOrEmpty(m))
    .ToList();
Console.WriteLine(string.Join(", ", results));
// => abc, (, {

The (\() regex matches and captures ( symbol into Capturing group 1, and thus the captured part is also output in the resulting string list.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563