Separating numbers from other signs in a string
I 开发者_StackOverflow社区got a string that contains:
"(" ")" "&&" "||"
and numbers (0 to 99999).
I want to get a string and return a list like this:
get:
"(54&&1)||15"
return new List<string>(){
"(",
"54",
"&&",
"1",
")",
"||",
"15"}
I suspect a regex would do the trick here. Something like:
string text = "(54&&1)||15";
Regex pattern = new Regex(@"\(|\)|&&|\|\||\d+");
Match match = pattern.Match(text);
while (match.Success)
{
Console.WriteLine(match.Value);
match = match.NextMatch();
}
The tricky bit in the above is that a lot of stuff needs escaping. The | is the alternation operator, so this is "open bracket or close bracket or && or || or at least one digit".
If you want to extract only numbers from your string you can use the regex
but if you want to parse this string and made some as formula and calculate result you should look at the math expression parser for example look at this Math Parser
Here's the LINQ/Lambda way to do it:
var operators = new [] { "(", ")", "&&", "||", };
Func<string, IEnumerable<string>> operatorSplit = t =>
{
Func<string, string, IEnumerable<string>> inner = null;
inner = (p, x) =>
{
if (x.Length == 0)
{
return new [] { p, };
}
else
{
var op = operators.FirstOrDefault(o => x.StartsWith(o));
if (op != null)
{
return (new [] { p, op }).Concat(inner("", x.Substring(op.Length)));
}
else
{
return inner(p + x.Substring(0, 1), x.Substring(1));
}
}
};
return inner("", t).Where(x => !String.IsNullOrEmpty(x));
};
Now you just call this:
var list = operatorSplit("(54&&1)||15").ToList();
Enjoy!
精彩评论