c#正則匹配取出文本內容 循環輸出

 

寫法1:正則表達式

private void GetRegexStr(string reString)
{
//注意 reString 請替換爲須要處理的字符串

string regexCode = "<li data-value=\"(.*?)\" title=\"(.*?)\" >\\s*<a href=\"#\" style=\"background:url\\((.*?)_40x40q90.jpg\\) center no-repeat;\">";
reg = new System.Text.RegularExpressions.Regex(regexCode);
System.Text.RegularExpressions.MatchCollection mc = reg.Matches(reString);
for (int i = 0; i < mc.Count; i++)
{

string temp = mc[i].Groups[1].Value;
string temp2= mc[i].Groups[2].Value;
string temp3 = mc[i].Groups[3].Value;

Console.WriteLine("skuid:"+temp);
Console.WriteLine("顏色分類:"+temp2);
Console.WriteLine("網址:"+temp3);


}
//須要獲取匹配的數據,請遍歷strList 一般狀況下(正則表達式中只有一個分組),只須要取strList[1]便可. 若是有多個分組,依次類推便可.


}

  寫法2ui

        /*調用方法: 直接粘貼內容至Code中,調用GetRegexStr("這裏填寫要處理的字符串")*/
        System.Text.RegularExpressions.Regex reg;//正則表達式變量
        /// <summary>
        /// 正則表達式獲取文本結果
        /// </summary>
        /// <param name="reString">請替換爲須要處理的字符串</param>
        /// <returns>處理結果</returns>
        private List<string> GetRegexStr(string reString)
        {
            //注意 reString 請替換爲須要處理的字符串
            List<string> strList = new List<string>();
            string regexCode = "<li data-value=\"(.*?)\" title=\"(.*?)\" >\\s*<a href=\"#\" style=\"background:url\\((.*?)_40x40q90.jpg\\) center no-repeat;\">";            
reg = new System.Text.RegularExpressions.Regex(regexCode);
           System.Text.RegularExpressions.MatchCollection mc = reg.Matches(reString);
            for (int i = 0; i < mc.Count; i++)
            {
                GroupCollection gc = mc[i].Groups; //獲得全部分組 
                for (int j = 1; j < gc.Count; j++) //多分組 匹配的原始文本不要
                {
                    string temp = gc[j].Value;
                    if (!string.IsNullOrEmpty(temp))
                    {
                        strList.Add(temp); //獲取結果   strList中爲匹配的值
                    }
                }
            }
            //須要獲取匹配的數據,請遍歷strList  一般狀況下(正則表達式中只有一個分組),只須要取strList[1]便可. 若是有多個分組,依次類推便可.
            return strList;
        }

  

 

---恢復內容結束---url

相關文章
相關標籤/搜索