Reputation: 9267
I want to split the following string
5 + 91 * 6 + 8 - 79
and as a result get an array which will save the all elements(including signs) in the same sequence
like this {5, +, 91, *, 6, +, 8, -, 79}
etc
I can not split it by space, because the string can be like this as well 5 + 91* 6+ 8 -79
or
without spaces at all 5+91*6+8-79
I tried this
string[] result = Regex.Split(str, @"[\d\+\-\*]{1,}");
but it returns nothing on cmd, when I try this
foreach (string value in result)
{
Console.WriteLine(value);
}
Upvotes: 1
Views: 167
Reputation: 32797
You can split it with this regex
(?<=\d)\s*(?=[+*/-])|(?<=[+*/-])\s*(?=\d)
Yes,it's long but it does split the string!
Upvotes: 0
Reputation: 149010
You can do this with a little Linq:
string[] result = Regex.Matches(str, @"\d+|[\+\-\*]")
.Cast<Match>().Select(m => m.Value).ToArray();
Or in query syntax:
string[] result =
(from m in Regex.Matches(str, @"\d+|[\+\-\*]").Cast<Match>()
select m.Value)
.ToArray();
Upvotes: 3
Reputation: 2013
You're looking for Matches()
:
string str = "5 + 91* 6+ 8 -79";
MatchCollection result = Regex.Matches(str, @"\d+|[\+\-\*]");
foreach (var value in result)
{
Console.WriteLine(value);
}
Console.ReadLine();
this gives you:
Upvotes: 3