如何修改正则以在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:
- 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. - Custom Evaluation Order: The
EvaluateLogicalOperatorsmethod 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. - Edge Cases: If your expressions include whitespace or custom values (not just
true/false), adjust the parsing logic inEvaluateLogicalOperatorsto match your data types.
内容的提问来源于stack exchange,提问作者user2150279

