正则统计词组出现次数

zwb521 2010-09-26 02:05:38
比如
string str="傻子|笨蛋"
string content="从前有一个傻子和一个笨蛋在一起玩耍,傻子吗笨蛋是笨蛋";

想用正则提取傻子笨蛋出现的次数
傻子出现2次,笨蛋出现3次

有难度啊
...全文
251 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
-过客- 2010-09-26
  • 打赏
  • 举报
回复
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";
大黄鸭在发光 2010-09-26
  • 打赏
  • 举报
回复
用递归实现

//判断字符串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;
}

}

porschev 2010-09-26
  • 打赏
  • 举报
回复
用正则效率不高。。

看看下面的。。

http://hi.baidu.com/zouqiner/blog/item/9043b6eef7d4d0e8ce1b3e09.html
Neil198 2010-09-26
  • 打赏
  • 举报
回复

string content = "从前有一个傻子和一个笨蛋在一起玩耍,傻子吗笨蛋是笨蛋";
Match m = Regex.Match(content , @"(?<sz>傻子)|(?<bd>笨蛋)");
m.Groups["sz"].Captures.Count;
m.Groups["bd"].Captures.Count;
zwb521 2010-09-26
  • 打赏
  • 举报
回复
谢谢,但想知道用正则怎么提取,我觉得应该可以的吧
kensouterry 2010-09-26
  • 打赏
  • 举报
回复
楼主应该把问题想得更简单一些,其实不是很难的!


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

}
zwb521 2010-09-26
  • 打赏
  • 举报
回复
厉害!真是牛叉
whb147 2010-09-26
  • 打赏
  • 举报
回复
没什么好办法
除了一个一个数,
嘿嘿

111,129

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧