如何进行非贪婪匹配?

diandian82 2013-01-08 11:14:53

static void Main(string[] args)
{
string content = "<div class=\"content\"><div class=\"img\">views:154140</span>"
+ "<div class=\"content\"><div class=\"img\">views:29387</span>"
+ "<div class=\"content\"><div class=\"img\">views:23232</span>";
var a = GetList(content);
}



public static List<string> GetList(string content)
{
Regex reg = new Regex("<div class=\"content\">[\\s\\S]*views[\\s\\S]*</span>", RegexOptions.IgnoreCase);
MatchCollection mc = reg.Matches(content, 0);
List<string> ret = new List<string>();
foreach (Match m in mc)
{
string s = m.Value;
ret.Add(s);
}
return ret;
}


以上代码匹配出来的结果是所有的Content,因为C#默认是贪婪匹配,我想要的结果是3组Match也就是非贪婪匹配,请问怎么做。我看网上说在前面加个? 但我加了?结果还是一样。

我把patten改成这样
Regex reg = new Regex("<div class=\"content\">[\\s\\S]*views[\\s\\S]*?</span>", RegexOptions.IgnoreCase);
结果还是全都出来了,请问怎么回事?
...全文
152 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
引用 3 楼 diandian82 的回复:
谢谢,可以解释一下吗?(?is)是什么意思?
i是忽略大小写 s是开启单行模式
diandian82 2013-01-09
  • 打赏
  • 举报
回复
谢谢,可以解释一下吗?(?is)是什么意思?
q107770540 2013-01-08
  • 打赏
  • 举报
回复

  public static List<string> GetList(string content)
		{
			Regex reg = new Regex(@"(?is)<div class=""content"">.*?views.*?</span>");
			return reg.Matches(content).Cast<Match>().Select(m=>m.Value).ToList();
		}
q107770540 2013-01-08
  • 打赏
  • 举报
回复
Try: Regex reg = new Regex("<div class=\"content\">[\\s\\S]*?views[\\s\\S]*?</span>", RegexOptions.IgnoreCase);

110,533

社区成员

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

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

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