c#正则匹配取出文本内容 循环输出
写法1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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]即可. 如果有多个分组,依次类推即可. } |
写法2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | /*调用方法: 直接粘贴内容至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; } |
---恢复内容结束---
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步