dav
dav

Reputation: 9267

split the string by numbers and signs c#

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

Answers (3)

Anirudha
Anirudha

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

p.s.w.g
p.s.w.g

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

Kai
Kai

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:

enter image description here

Upvotes: 3

Related Questions