Reputation: 165
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?
Upvotes: 3
Views: 1268
Reputation: 626826
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.
Upvotes: 2