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?
Asked
Active
Viewed 1,217 times
3

vertigo
- 125
- 8
-
what if you have this: `abc((({` and you split by `(`, what do you want in the result? – CodingYoshi Jan 06 '17 at 16:48
-
i always want to keep the delimiters so `{ abc , ( , ( , ( , { }` – vertigo Jan 06 '17 at 17:20
-
Use `var results = System.Text.RegularExpressions.Regex.Split(s, @"(\()").Where(m=>!string.IsNullOrEmpty(m));` – Wiktor Stribiżew Jan 06 '17 at 17:54
-
For multiple delimiters, just add them to the regex. To split with `{` and `(`, use `@"([({])"` regex. To split with `abc`, `{` and `(`, use `@"(abc|[{(])"` – Wiktor Stribiżew Mar 28 '17 at 12:03
1 Answers
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