首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

正则表达式的写法,该如何处理

2012-08-09 
正则表达式的写法在网上获取到的字符串为 tabletrth姓名/thth身高/thth年纪/thth学历/

正则表达式的写法
在网上获取到的字符串为 <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); 

热点排行