5.5. 从字符串中提取单个的子字符串:extractSingleStr


//using Regex to extract single string value
// caller should make sure the string to extract is Groups[1] == include single () !!!
public bool extractSingleStr(string pattern, string extractFrom, out string extractedStr)
{
    bool extractOK = false;
    Regex rx = new Regex(pattern);
    Match found = rx.Match(extractFrom);
    if (found.Success)
    {
        extractOK = true;
        extractedStr = found.Groups[1].ToString();
    }
    else
    {
        extractOK = false;
        extractedStr = "";
    }

    return extractOK;
}

    

例 5.5. extractSingleStr 的使用范例


string resPreloadUrl = "";
//var srf_uPreload = 'https://skydrive.live.com/handlers/resourcespreload.mvc?view=Folders.All&id;=250206&mkt;=EN-US';
string resPreloadP = @"var\ssrf_uPreload\s=\s'(.+?)';";
extractSingleStr(resPreloadP, html, out resPreloadUrl);

        


[注意]传入extractSingleStr的正则pattern中必须包含括号,即group

从代码中可见,传入extractSingleStr中的pattern,必须有一个括号,即一个group

然后查找出来的内容,才能得以提取出来