比如
string str="傻子|笨蛋
string content="从前有一个傻子和一个笨蛋在一起玩耍,傻子吗笨蛋是笨蛋";想用正则提取傻子笨蛋出现的次数
傻子出现2次,笨蛋出现3次有难度啊

解决方案 »

  1.   

    楼主应该把问题想得更简单一些,其实不是很难的!
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Collections;namespace ConsoleApplication1
    {
        class Program
        {
            string content = "从前有一个傻子和一个笨蛋在一起玩耍,傻子吗笨蛋是笨蛋";
            //因为傻子和笨蛋都是两个词,所以位置是紧靠一起的
            char[] fool1 = new char[2] {'傻','子' };
            char[] fool2 = new char[2] { '笨', '蛋' };        public Program()
            {
                int fool1Count = 0;
                int fool2Count = 0;            //arrayList中记录了整段话的所有数据
                char[] arrayList = content.ToCharArray();
                //接下来对每个字依次对比
                for (int i = 0; i < arrayList.Length -1; i++)
                {
                    if (arrayList[i] == fool1[0] && arrayList[i+1]==fool1[1])
                    {
                        fool1Count++;
                    }
                    if (arrayList[i] == fool2[0] && arrayList[i + 1] == fool2[1])
                    {
                        fool2Count++;
                    }
                }
                //fool1Count代表“傻子”的次数,fool2Count代表“笨蛋”的次数
                Console.WriteLine("fool1 times={0},fool2 times={1}", fool1Count, fool2Count);
            }        static void Main()
            {
                Program p1 = new Program();            Console.ReadLine();
            }
        }}
      

  2.   


    string content = "从前有一个傻子和一个笨蛋在一起玩耍,傻子吗笨蛋是笨蛋";
     Match m = Regex.Match(content , @"(?<sz>傻子)|(?<bd>笨蛋)");
                m.Groups["sz"].Captures.Count;
                m.Groups["bd"].Captures.Count;
      

  3.   

    用正则效率不高。。看看下面的。。http://hi.baidu.com/zouqiner/blog/item/9043b6eef7d4d0e8ce1b3e09.html
      

  4.   

    用递归实现//判断字符串compare 在 input字符串中出现的次数
     private static int GetStringCount(string input, string compare)
            {
                int index = input.IndexOf(compare);
                if (index != -1)
                {
                    return 1 + GetStringCount(input.Substring(index + compare.Length), compare);
                }
                else
                {
                    return 0;
                }        }
      

  5.   

    try...string content = "从前有一个傻子和一个笨蛋在一起玩耍,傻子吗笨蛋是笨蛋";
    Match m = Regex.Match(content, @"(?s)(?:(傻子)|(笨蛋)|(?!傻子|笨蛋).)+");
    richTextBox2.Text += "\"傻子\"出现次数:" + m.Groups[1].Captures.Count + "\n";
    richTextBox2.Text += "\"笨蛋\"出现次数:" + m.Groups[2].Captures.Count + "\n";