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

正则表达式的写法
在网上获取到的字符串为 <table><tr><th>姓名</th><th>身高</th><th>年纪</th><th>学历</th> </tr><tr><td>张三</td><td>198厘米</td><td>25</td> <td>小学</td></tr><tr><td>李四</td><td>178厘米</td><td>18</td><td>大学</td></tr></table>

用正则表达式得出以下结果

序号:1
姓名:张四
身高:198厘米
年纪:25
学历:小学

序号:2
姓名:李四
身高:178厘米
年纪:18
学历:大学
...

------解决方案--------------------
C# code

            StreamReader reader = new StreamReader("c:\\1.txt",Encoding.Default);
            string source = reader.ReadToEnd();
            Regex reg = new Regex(@"(?is)(?<=<td>).*?(?=</td>)");
            MatchCollection mc = reg.Matches(source);
            foreach (Match m in mc)
            {
                MessageBox.Show(m.Groups["value"].Value);
            }
上面正则取到
/*
张三
198
厘米
25
小学
李四
178
厘米
18
大学
*/

------解决方案--------------------
C# code

Regex reg = new Regex(@"(?i)<tr>\s*<td>([^<]*)</td>\s*<td>([^<]*)</td>\s*<td>([^<]*)</td>\s*<td>([^<]*)</td>\s*</tr>");
MatchCollection mc = reg.Matches(yourStr);
foreach (Match m in mc)
{
    richTextBox2.Text += "姓名:" + m.Groups[1].Value + "\n";
    richTextBox2.Text += "身高:" + m.Groups[2].Value + "\n";
    richTextBox2.Text += "年纪:" + m.Groups[3].Value + "\n";
    richTextBox2.Text += "学历:" + m.Groups[4].Value + "\n---------------\n";
}
/*-----输出-----
姓名:张三
身高:198厘米
年纪:25
学历:小学
---------------
姓名:李四
身高:178厘米
年纪:18
学历:大学
---------------
*/

------解决方案--------------------
两次匹配
首先,通过(?i)<th>(.*?)</th>获取姓名、身高等,
然后,通过(?i)<tr>\s*<td>([^<]*)</td>\s*<td>([^<]*)</td>\s*<td>([^<]*)</td>\s*<td>([^<]*)</td>\s*</tr>获取相应的数据
C# code

Regex reg1 = new Regex(@"(?i)<th>(.*?)</th>");
Regex reg2 = new Regex(@"(?i)<tr>\s*<td>([^<]*)</td>\s*<td>([^<]*)</td>\s*<td>([^<]*)</td>\s*<td>([^<]*)</td>\s*</tr>");
List<string> listTitle=new List<string>();
Dictionary<string,string> dicValue=new Dictionary<string,string>();
MatchCollection mc1 = reg1.Matches(yourStr);
foreach (Match m in mc1)
{
 listTitle.Add(m.Groups[1].Value);
}
int i=0;
MatchCollection mc2 = reg2.Matches(yourStr);
foreach (Match m in mc2&&i<mc2.Count)
{
   dicValue.Add(list[i],m.Groups[i].Value);
   i++;
}

------解决方案--------------------
C# code
            string str = @"
<table>
<tr>
<th>姓名</th><th>身高</th><th>年纪</th><th>学历</th> </tr>

<tr>
<td>张三</td>
<td>198厘米</td>
<td width=""20"">25</td>  
<td width=""20"">小学</td></tr>
<tr>
<td>李四</td>
<td>178厘米</td>
<td width=""20"">18</td>
<td width=""20"">大学</td>
</tr>
</table>";
            Regex reg = new Regex(@"(?is)<tr>\s*<td>(.*?)</td>\s*<td>.*?</td>\s*<td[^>]*?>(.*?)</td>.*?</tr>");
            foreach (Match m in reg.Matches(str))
                Console.WriteLine("{0}:{1}", m.Groups[1].Value, m.Groups[2].Value);