Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将数字与字符串中的其他符号分开_C#_String_Algorithm - Fatal编程技术网

C# 将数字与字符串中的其他符号分开

C# 将数字与字符串中的其他符号分开,c#,string,algorithm,C#,String,Algorithm,我得到一个字符串,其中包含: "(" ")" "&&" "||" 和数字0至99999 我想获取一个字符串并返回如下列表: 获取: 我怀疑正则表达式会在这里起作用。比如: string text = "(54&&1)||15"; Regex pattern = new Regex(@"\(|\)|&&|\|\||\d+"); Match match = pattern.Match(text); while (match.Success) {

我得到一个字符串,其中包含:

"("  ")"  "&&"  "||"
和数字0至99999

我想获取一个字符串并返回如下列表:

获取:


我怀疑正则表达式会在这里起作用。比如:

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();
}

上面的棘手之处在于,很多东西都需要逃离。|是交替运算符,因此这是开括号或闭括号或&&或| |或至少一个数字。

如果只想从字符串中提取数字,可以使用正则表达式

但是,如果您想解析这个字符串,并将其作为公式和计算结果,您应该查看数学表达式解析器
例如,看看这个

以下是LINQ/Lambda的方法:

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));
};
享受吧

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));
};
var list = operatorSplit("(54&&1)||15").ToList();