<table title="123">   
    <tr>   
      <td>   
        <table>   
          <tr>   
            <td>内容</td>   
          </tr>   
        </table>   
      </td>   
    </tr>   
  </table>
<table>   
          <tr>   
            <td>内容2</td>   
          </tr>   
      </table>   请问,如何用正则表达式找出title为“123”的table?

解决方案 »

  1.   

    其实这一类问题我已经在下面这个帖子里给出解决方案了,只不过没有多少人愿意去研究罢了
    【分享】正则平衡组应用场景分析及性能优化
    Regex reg = new Regex(@"(?is)
                          <table(?:(?!title=).)*title=""123""[^>]*>        #开始标记“<table...>”
                              (?>                         #分组构造,用来限定量词“*”修饰范围                                            
                                  <table[^>]*>  (?<Open>)   #命名捕获组,遇到开始标记,入栈,Open计数加1
                              |                           #分支结构
                                  </table>  (?<-Open>)      #狭义平衡组,遇到结束标记,出栈,Open计数减1
                              |                           #分支结构
                                  (?:(?!</?table\b).)*      #右侧不为开始或结束标记的任意字符
                              )*                          #以上子串出现0次或任意多次
                              (?(Open)(?!))               #判断是否还有'OPEN',有则说明不配对,什么都不匹配
                          </table>                          #结束标记“</table>”
                         ", RegexOptions.IgnorePatternWhitespace);
    MatchCollection mc = reg.Matches(test);
    foreach (Match m in mc)
    {
         richTextBox2.Text += m.Value + "\n--------------------\n";
    }实际应用中可以把注释去掉目前没测试环境,楼主先测下吧
      

  2.   

    去了注释的Regex reg = new Regex(@"(?is)<table(?:(?!title=).)*title=""123""[^>]*>(?><table[^>]*>(?<Open>)|</table>(?<-Open>)|(?:(?!</?table\b).)*)*(?(Open)(?!))</table>");
    MatchCollection mc = reg.Matches(test);
    foreach (Match m in mc)
    {
         richTextBox2.Text += m.Value + "\n--------------------\n";
    }
      

  3.   

    过客正则就是厉害
    用<tr[^>]*>(?:(?:\s|\S)*?(?=<table|</tr>)(?(<table)<table[^>]*>(?:\s|\S)*?(?:</table>|(?:(?:<table[^>]*>(?:\s|\S)*?</table>(?:\s|\S)*?)*?</table>))(?:\s|\S)*?|))*</tr>
    试试