Suppose I had the string “1 AND 2 AND 3 OR 4”, and want to create an array of strings that contains all substrings “AND” or “OR”, in order, found within the string.
So the above string would return a string array of {“AND”, “AND”, “OR”}.
What would be a smart way of writing that?
EDIT:
Using C# 2.0+,
string rule = "1 AND 2 AND 3 OR 4";
string pattern = "(AND|OR)";
string[] conditions = Regex.Split(rule, pattern);
gives me {“1”, “AND”, “2”, “AND”, “3”, “OR”, “4”}, which isn’t quite what I’m after. How can I reduce that to the ANDs and ORs only?
This regex (.NET) seems to do what you want. You’re looking for the matches (multiple) in the group at index=1:
EDIT I’ve tested the following and it seems to do what you want. It’s more lines than i would like but it approaches the task in a purely regex fashion (which IMHO is what you should be doing):