C #: finding instances of a string within a string

Suppose I had the string "1 AND 2 AND 3 OR 4" and you want to create an array of strings that contains all the substrings "AND" or "OR", in order, found within the string.

So the above string will return an array of strings of {"AND", "AND", "OR"}.

What would be a sane way to write this?

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 is not exactly what I want. How can I reduce this for AND and OR only?

0


a source to share


5 answers


This regex (.NET) seems to do what you want. You are looking for matches (multiple) in the group at index = 1:

.*?((AND)|(OR))*.*?

      



EDIT I've tested the following and it seems to do what you want. This is more lines than I would like, but it fits the job in a pure regex (which IMHO is what you should be doing):

        string text = "1 AND 2 AND 3 OR 4";
        string pattern = @"AND|OR";

        Regex r = new Regex(pattern, RegexOptions.IgnoreCase);

        Match m = r.Match(text);
        ArrayList results = new ArrayList();
        while (m.Success)
        {
            results.Add(m.Groups[0].Value);

            m = m.NextMatch();
        }

        string[] matchesStringArray = (string[])results.ToArray(typeof(string));

      

+1


a source


You are probably looking for a tokenizer or Lexer, see the following article:



C # Regular Expression Recipes - Best Tokenizer

+1


a source


Since you know the exact substring you are looking for, why not just use IndexOf (substr, iOffset) to know the number of events (loop until it returns -1)

Depending on the complexity of your task, this might be easier / faster than using regular expressions (since you don't match patterns).

+1


a source


string rule = "1 AND 2 AND 3 OR 4";
string pattern = "(AND|OR)";
MatchCollection conditions = Regex.Matches(rule, pattern);

      

Use Match.Value to get a string.

+1


a source


Here is the dumb way I came up with:

string rule = "1 AND 2 AND 3 OR 4";
List<string> andsOrs = new List<string>();
string[] split = rule.Split();
for (int i = 0; i < split.Length; i++)
{
   if (split[i] == "AND" || split[i] == "OR")
   {
       andsOrs.Add(split[i]);
   }
}
string[] conditions = andsOrs.ToArray();
return conditions;

      

0


a source







All Articles