kosnkov
kosnkov

Reputation: 5911

Split string and keep separator as new result item

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

Answers (3)

DK.
DK.

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

Guffa
Guffa

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

D Stanley
D Stanley

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

Related Questions