1

i must use regex for part of my project. I want to seperate for AND,OR operators from given inputs. But i don't need operators which are situated in parentheses.

Example input : C1 OR [C2 AND C3] AND C4 OR C5 AND [C6 AND C7 OR C8 ] OR C9

Output : OR AND OR AND OR

Other Example input : C1 AND C2 AND [C3 OR C4] AND C5

Output : AND AND AND

s952163
  • 6,276
  • 4
  • 23
  • 47
  • 4
    So, what did you try.. if you "must" use regex, that sounds like homework – BugFinder Jul 19 '16 at 07:56
  • If you have deeply nested parentheses groups like `((((a AND b) OR c) AND d) OR e) AND f` you'll have a headache and tend to regex hell. So if you are able to avoid regex, consider use of [Abstract Syntax Tree](https://en.wikipedia.org/wiki/Abstract_syntax_tree), you can use finite state machine to track parenthesis group open/close status and recursive algorithm to parse your string into tree. – Vladimir Vagaytsev Jul 19 '16 at 08:37
  • I write "must" use regex. Because i tried to split methods but it did not solve my problem. Also i tried to regex but i can not seperate which parentheses and their includes. – M.Emin Yıldız Jul 19 '16 at 09:12
  • 1
    Do you have nested parentheses? Do you really have to use regex, or does any another algorithm that works suffice for you? – Mario Dekena Jul 19 '16 at 09:21

1 Answers1

0

If you dont have nested parantheses you can do it this way:

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

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            var input = "1 OR[C2 AND C3] AND C4 OR C5 AND[C6 AND C7 OR C8] OR C9";
            var filtered = Regex.Replace(input, "\\[.*?\\]", string.Empty);
            var result = filtered.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Where(element => element == "OR" || element == "AND");
            Console.WriteLine(string.Join(", ", result));
            Console.ReadKey();
        }
    }
}
Mario Dekena
  • 843
  • 6
  • 20