日期:2014-05-18  浏览次数:20498 次

同志们,搞了一天了。关于C#中的正则问题
如题,一个简简单单的正则硬是折腾了我很久。
现在帖出代码和结果,请各位分析,提供点意见

源码是这段,我已经取出来了,我放在1楼,在线等着。其实不复杂,我只取里面的<td width=10%></td><td width=60%></td>里的内容,请各位帮着看看,看哪里有错,我是找不到了,找了一天了。我的程序还有没有什么不妥的,也请提出来。分不够再加。


 private void getdetailurl(string detailurl)
  {  
  string regdetail = @"<DIV class=p3\>(.*?)\<div";
  Regex reg_detail_part = new Regex(@"\<TD width=.*30%.*\>(.*?)\<\/TD\>\<TD width=.*60%.*\>(.*?)\<\/TD\>", RegexOptions.IgnoreCase);
  Match match_detailurl ;  
  detailurl = Regex.Match(detailurl, regdetail).Groups[1].ToString();
  pdSpecOption = detailurl;
  match_detailurl = reg_detail_part.Match(detailurl);
  string[] getpdattr = new string [100];
  string[] getpdtext = new string[100];
  int i=0;
   
  for (
  i=0;
  match_detailurl.Success && i<100 ;
  match_detailurl.NextMatch()
  )
  {
  getpdattr[0] = match_detailurl . Groups[1] . ToString() ;
  getpdtext[0] = match_detailurl . Groups[2] . ToString() ;
  }
  pdsec = getpdattr[0];  
  //pdSpecOption = getpdtext[0];
  specs = getpdtext[0];
  }


运行后的结果是这样:
GROUPS[1]是正确的,但是GRROUP[2]为空,程序也不报错。
不知道是正则有问题,还是别的什么。

------解决方案--------------------
没看明白LZ要什么?你自己下一个正则匹配工具来看看是不是你的正则有问题
------解决方案--------------------
你的正则也就两组
而组索引是0开始
所以应该是 group[0]group[1]
------解决方案--------------------
正则不会(惭愧),帮顶。
------解决方案--------------------
楼主是从其它语言转到C#的吗?

C# code
//这里的detailurl为过滤后的detailurl
MatchCollection mc = Regex.Matches(detailurl, @"<td\s*width=['""]?\s*30%[^>]*>([\s\S]*?)</td>\s*<td\s*width=['""]?\s*60%[^>]*>([\s\S]*?)</td>", RegexOptions.IgnoreCase);
foreach (Match m in mc)
{
    Console.WriteLine(m.Groups[1].Value);
    Console.WriteLine(m.Groups[2].Value);
}