日期:2014-05-16  浏览次数:20944 次

正则表达式匹配数据,高手进!
最近看了个模拟百度登陆的贴子,那大神把源码也贴出来了,可调试发现找不到匹配数据,现代码贴出来,高手帮指正一下;

//获取token值
private void btnGetToken_Click(object sender, EventArgs e)
{
    if (gotCookieBaiduid)
    {
        string getapiUrl = "https://passport.baidu.com/v2/api/?getapi&class=login&tpl=mn&tangram=true";
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(getapiUrl);
  
        //add previously got cookies
        req.CookieContainer = new CookieContainer();
        req.CookieContainer.Add(curCookies);
  
        req.Method = "GET";
        HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
        StreamReader sr = new StreamReader(resp.GetResponseStream());
        string respHtml = sr.ReadToEnd();
  
        //bdPass.api.params.login_token='5ab690978812b0e7fbbe1bfc267b90b3';(需要把token值获取)
        string tokenValP = @"bdPass\.api\.params\.login_token='(?<tokenVal>\w+)';";
        Match foundTokenVal = (new Regex(tokenValP)).Match(respHtml);
        if (foundTokenVal.Success)
        {
            //extracted the token value
            txbExtractedTokenVal.Text = foundTokenVal.Groups["tokenVal"].Value;
            extractTokenValueOK = true;
        }
        else
        {
            txbExtractedTokenVal.Text = "错误:没有找到token的值!";
        }
  
    }
    else
    {
        MessageBox.Show("错误:之前没有正确获得Cookie:BAIDUID !");
    }
}

主要是这里没找到
 string tokenValP = @"bdPass\.api\.params\.login_token='(?<tokenVal>\w+)';";
        Match foundTokenVal = (new Regex(tokenValP)).Match(respHtml);
大神们请帮下忙,先多谢了.
------解决方案--------------------
_无需转义
string str = @"bdPass.api.params.login_token='5ab690978812b0e7fbbe1bfc267b90b3'";

            string value = Regex.Match(str, @"(?i)(?<=login_token=['""])[^'""]+").Value;//"5ab690978812b0e7fbbe1bfc267b90b3"

------解决方案--------------------

        string tokenValP = @"token='(.+?)';";
        Match foundTokenVal =&nbs