convert logical expression string into string array, based on parenthesis
我有一个使我感到困惑的问题,我无法弄清楚如何在C#中做到这一点。
比方说,我有这个公式:
这只是一个示例公式,但可能会更复杂,例如:
我想将其分为三个部分
以另一种方式,我想将此公式分为两个部分公式和其操作数。现在,我有两个二元运算符(or,and)和一个一元运算符(not)。
我该如何解决这个问题?你能帮我这个忙吗?我已经尝试过使用分组构造的正则表达式,但是我不是正则表达式的专家。
谢谢,
奥托
这个问题只能解决。反向波兰语符号(RPN)
将您的字符串转换为RNP,然后执行它。
奥托(Otto),不知道为什么要这么做,我不知道字符串数组是否是最好的方法。问题是,如果仅具有"(true or false)"等数组,则会丢失原始表达式的结构。我的解决方案使用从0开始的整数作为占位符,以显示从表达式中提取字符串的位置。希望这可以帮助!格雷格
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | using System; using System.Collections.Generic; namespace ParseParentheses { class Program { static List<string> wordList = new List<string>(); static int wordIndex = -1; static void Main(string[] args) { GetChunks("(true AND (true OR false)) OR ((true AND false) OR false)"); // Now we know how many items we have, convert the List to an array, // as this is what the solution specified. string[] words = wordList.ToArray(); for (int i = 0; i < words.Length; i++) { Console.WriteLine(i +":\\t" + words[i]); } } private static void GetChunks(string text) { int start; int end = text.IndexOf(')'); if (end > -1) { start = text.LastIndexOf('(', end - 1); if (start == -1) { throw new ArgumentException("Mismatched parentheses", text); } wordList.Add(text.Substring(start, end - start + 1)); wordIndex++; text = text.Substring(0, start) + wordIndex.ToString() + text.Substring(end + 1); GetChunks(text); } else { // no more ) in text, just add what's left to the List. wordList.Add(text); } } } } |