C#: finding instances of a string within a string

前端 未结 5 1415
心在旅途
心在旅途 2021-01-28 01:28

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.

<
5条回答
  •  -上瘾入骨i
    2021-01-28 01:55

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

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

    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):

            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));
    

提交回复
热议问题