0

嗨,我正在尝试从下面的标签中获取结果,我需要实现的是在标签中获得第一个匹配,然后是第五个匹配,然后是第九个匹配,所以是第一个,然后是每第五个匹配。所以我的结果是,注意我意识到这不是解析 HTML 的最佳方式,但我真的只需要它

我正在使用的正则表达式是

<td class="stat">(.*?)<\/td>

我正在使用的代码是

private static ObservableCollection<Top> top = new ObservableCollection<Top>();
    
public void twit_topusers_DownloadStringCompleted(Object sender, DownloadStringCompletedEventArgs e)
    {
            string str;
            // Size the control to fill the form with a margin
            str = (string)e.Result;



             
            Regex r = new Regex("<td class=\"stat\">(.*?)</td>");
            // Find a single match in the string.
            Match m = r.Match(str);
            




            while (m.Success)
            {

                testMatch = "";

                //
                testMatch += System.Text.RegularExpressions.Regex.Unescape(m.Groups[0].ToString()).Trim();

                

                top.Add(new Top(testMatch));
                m = m.NextMatch();

            }

            listBox.ItemsSource = top;
        
        
    }



    }

标签是

<td class="stat">14307149</td>//FIRST
<td class="stat">679761</td>
<td class="stat">3508</td>
<td class="stat">62 months ago</td>
<td class="stat">1430700</td>//FIFTH
<td class="stat">679761</td>
<td class="stat">3508</td>
<td class="stat">72 months ago</td>
<td class="stat">1430600</td>//NINTH
<td class="stat">679761</td>
<td class="stat">3508</td>
<td class="stat">82 months ago</td>

但我得到的结果是

匹配 1 14307149

比赛 2 679761

第 3 场比赛 3508

第 4 场比赛 62 个月前

匹配 5 1430700

比赛 6 679761

比赛 7 3508

第 8 场比赛 72 个月前

比赛 9 14307149

比赛 10 679761

比赛 11 3508

第 12 场比赛 62 个月前

我需要的结果是

匹配 1 14307149

匹配 2 1430700

匹配 3 1430600

你能帮我解决这个问题吗?

4

2 回答 2

2

看起来您根本没有检查行号。如果您只是添加一个计数器,然后检查其 4 的 mod 是否为零,您会很好。

counter = 0;
while (m.Success)
{
        if( counter % 4 == 0 )
        {
            testMatch = "";

            //
            testMatch += System.Text.RegularExpressions.Regex.Unescape(m.Groups[0].ToString()).Trim();



            top.Add(new Top(testMatch));
            m = m.NextMatch();

        }
        counter++;
}

注意:我不是 WP7 开发人员,因此根据 WP7 编码系统的工作方式,此代码可能会略有偏差。

于 2012-04-18T23:06:43.973 回答
0

将其更改如下以仅匹配数字:

     <td class="stat">(\d+)<\/td>

如果我理解正确,您必须先拆分字符串months ago,然后通过上述正则表达式匹配拆分操作的结果。

于 2012-04-18T23:02:25.977 回答