You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改正则以在C#中求值含|和&的自定义括号表达式

Hey there! Let's break this down for you clearly.

First off, the regex you're using—\(([^()]*)\)—actually already supports | and & characters out of the box! The [^()] part is a negated character class that matches any character except ( and ), which includes your logical operators | and & automatically. So if you're trying to extract the innermost parenthetical content (like a|b from ((a|b)&c)), this regex will work perfectly for that.

The real challenge isn't modifying the regex—it's building the logic to evaluate these nested expressions in your desired order. Let's walk through a practical C# implementation that uses this regex to handle nested brackets, then evaluates the logical operators according to your rules:

using System;
using System.Text.RegularExpressions;
using System.Linq;

public class CustomExpressionEvaluator
{
    public static string Evaluate(string inputExpression)
    {
        // Regex to match innermost parentheses (works with |, &, and any non-bracket chars)
        var innerBracketRegex = new Regex(@"\(([^()]*)\)");
        
        // Process nested brackets from innermost to outermost
        while (innerBracketRegex.IsMatch(inputExpression))
        {
            inputExpression = innerBracketRegex.Replace(inputExpression, match => 
            {
                // Extract the content inside the innermost brackets (e.g., "true|false&true")
                string innerExpr = match.Groups[1].Value;
                // Evaluate this inner expression using your custom order/rules
                return EvaluateLogicalOperators(innerExpr);
            });
        }
        
        // Evaluate any remaining top-level expression
        return EvaluateLogicalOperators(inputExpression);
    }

    private static string EvaluateLogicalOperators(string expr)
    {
        // Replace this with your actual evaluation logic!
        // Example: We'll prioritize & (AND) over | (OR) as is standard, but you can reverse this
        expr = expr.Replace(" ", ""); // Clean up any whitespace
        
        // First process all AND operations
        while (expr.Contains("&"))
        {
            var andMatch = Regex.Match(expr, @"([^&|]+)&([^&|]+)");
            if (!andMatch.Success) break;
            
            // Simulate AND logic (replace with your actual value checking)
            bool left = bool.Parse(andMatch.Groups[1].Value);
            bool right = bool.Parse(andMatch.Groups[2].Value);
            expr = expr.Replace(andMatch.Value, (left && right).ToString());
        }
        
        // Then process all OR operations
        while (expr.Contains("|"))
        {
            var orMatch = Regex.Match(expr, @"([^&|]+)\|([^&|]+)");
            if (!orMatch.Success) break;
            
            // Simulate OR logic (replace with your actual value checking)
            bool left = bool.Parse(orMatch.Groups[1].Value);
            bool right = bool.Parse(orMatch.Groups[2].Value);
            expr = expr.Replace(orMatch.Value, (left || right).ToString());
        }
        
        return expr;
    }

    public static void Main()
    {
        string testExpr = "((true|false)&(true&false))";
        string result = Evaluate(testExpr);
        Console.WriteLine($"Result: {result}"); // Outputs "false"
    }
}

Key Notes:

  1. Regex Behavior: The original regex works for your use case because [^()] doesn't exclude | or &—it only skips parentheses, which is exactly what you want for extracting innermost bracket content.
  2. Custom Evaluation Order: The EvaluateLogicalOperators method above processes & first, then |, but you can easily reverse this (or implement left-to-right evaluation regardless of priority) by swapping the order of the while loops.
  3. Edge Cases: If your expressions include whitespace or custom values (not just true/false), adjust the parsing logic in EvaluateLogicalOperators to match your data types.

内容的提问来源于stack exchange,提问作者user2150279

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:51:39