Reputation: 5911
Having string like 11+2-33
I need to split it into 11,+,2,-,33
this produce me 11+,2-,33
Regex.Split(input, @"(?<=[+,-])")
so I need to apply it again on each result item, is there better way ?
Upvotes: 1
Views: 125
Reputation: 3243
You need both look-behind and look-ahead, just as you've said:
var matches = Regex.Split("11+2-33", "(?<=[+-])|(?=[+-])");
Console.WriteLine(string.Join(",", matches));
11,+,2,-,33
Upvotes: 4
Reputation: 700232
You can use a regular expression that matches either a number or an operator. Example:
string expression = "11+2-33";
string[] parts =
Regex.Matches(expression, @"\d+|[+-]").Cast<Match>().Select(m => m.Value).ToArray();
foreach (string s in parts) Console.WriteLine(s);
Output:
11
+
2
-
33
Upvotes: 3
Reputation: 152521
I'm not a regex expert, so there may be a clever way to do it with a regex, matches, etc., but how I would do it is add delimiters:
string s = "11+2-33";
s = s.Replace("+","|+|");
s = s.Replace("-","|-|");
string[] parts = s.Split('|');
You can refactor from there but that's the general idea.
Upvotes: 1