/* * 常用正则表达式 * 肖俊 * 2013-5-2 * */ using System; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace AllBase { /// /// 基础正则表达式类 /// public static class BaseRegex { /// /// 返回正则对象所有结果 /// /// /// /// public static MatchCollection GetMatchRegex(string HtmlString, string RegexString) { if (HtmlString == null) { LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + RegexString); return null; } return Regex.Matches(HtmlString, RegexString, RegexOptions.IgnoreCase); } /// /// 返回正则对象所有结果 /// /// /// /// public static MatchCollection GetMatchRegex(ref string HtmlString, string RegexString) { if (HtmlString == null) { LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + RegexString); return null; } return Regex.Matches(HtmlString, RegexString, RegexOptions.IgnoreCase); } /// /// 返回单个正则分析结果 /// /// /// /// public static string GetMatchRegexString(ref string HtmlString, string RegexString) { if (HtmlString == null) { LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + RegexString); return null; } MatchCollection mc = Regex.Matches(HtmlString, RegexString, RegexOptions.IgnoreCase); if (mc.Count > 0) { return mc[0].Groups[1].Value.ToString(); } return null; } /// /// 返回单个正则分析结果 /// /// /// /// public static string GetMatchMaxRegexString(ref string HtmlString, string RegexString) { if (HtmlString == null) { LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + RegexString); return null; } MatchCollection mc = Regex.Matches(HtmlString, RegexString, RegexOptions.IgnoreCase); if (mc.Count > 0) { return mc[mc.Count - 1].Groups[1].Value.ToString(); } return null; } /// /// 返回匹配的数值 /// /// /// /// public static int GetMatchInt(ref string HtmlString, string RegexString) { string id = GetMatchRegexString(ref HtmlString, RegexString); int i; int.TryParse(id, out i); return i; } /// /// 返回单个正则分析结果 /// /// /// /// public static string GetMatchRegexString(string HtmlString, string RegexString) { if (HtmlString == null) { LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + RegexString); return null; } MatchCollection mc = Regex.Matches(HtmlString, RegexString, RegexOptions.IgnoreCase); if (mc.Count > 0) { return mc[0].Groups[1].ToString(); } return null; } /// /// 是否存在匹配 /// /// /// /// public static bool MatchRegex(string HtmlString, string RegexString) { if (HtmlString == null) { LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + RegexString); return false; } return Regex.IsMatch(HtmlString, RegexString, RegexOptions.IgnoreCase); } /// /// 根据正则删除表达式所匹配的内容 /// /// /// /// public static string Clear(string HtmlString, string RegexString) { if (HtmlString == null) { LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + RegexString); return null; } return Regex.Replace(HtmlString, RegexString, "", RegexOptions.IgnoreCase); } /// /// 清除HTML代码 /// /// /// 返回文字内容 public static string ClearHtml(string HtmlString) { if (HtmlString == null) { LogSave.Add("匹配正则发生错误:原始字符串为空"); return null; } return Regex.Replace(Regex.Replace(HtmlString, @"(|||)", ""), "(<[^>]*?>)", "").Trim(); } /// /// 清除HTML代码 /// /// /// 返回文字内容 public static string ClearHtml(ref string HtmlString) { if (HtmlString == null) { LogSave.Add("匹配正则发生错误:原始字符串为空"); return null; } return Regex.Replace(Regex.Replace(HtmlString, @"(|||)", ""), "(<[^>]*?>)", "").Trim(); } /// /// 清除HTML代码 /// /// /// 返回文字内容 public static void ClearHtmlX(ref string HtmlString) { if (string.IsNullOrEmpty(HtmlString)) { LogSave.Add("匹配正则发生错误:原始字符串为空"); return; } HtmlString = Regex.Replace(Regex.Replace(HtmlString, @"(|||)", ""), "(<[^>]*?>)", ""); } /// /// 清除HTML代码A标签 /// /// /// 返回文字内容 public static string ClearA(string HtmlString) { if (HtmlString == null) { LogSave.Add("匹配正则发生错误:原始字符串为空"); return null; } HtmlString = Regex.Replace(HtmlString, "(]*>)", "", RegexOptions.IgnoreCase); return HtmlString.Trim(); } /// /// 去除空格和特殊空白 /// /// /// public static string Trim(string text) { if (string.IsNullOrEmpty(text)) return ""; return text.Replace("\t", " ").Replace("\r\n", " ").Replace("\r", " ").Replace("\n", " ").Trim(); } /// /// 清除HTML代码A标签 /// /// /// 返回文字内容 public static string ClearTitle(string HtmlString) { if (HtmlString == null) { LogSave.Add("匹配正则发生错误:原始字符串为空"); return null; } HtmlString = Regex.Replace(HtmlString, "(title=\"[^\"]*\")", ""); return HtmlString.Trim(); } /// /// 获取值 /// /// /// /// public static string GetValue(string html, string reg) { return GetMatchRegexString(html, "<" + reg + ">([^<]+)"); } /// /// 清理多余的HTML元素 /// /// /// public static string ClearNone(string html) { if (string.IsNullOrEmpty(html)) return null; if (html.Contains("\0") && html.IndexOf("\0") > 0) html = html.Substring(0, html.IndexOf("\0")); string h = Clear(html, @"(<\!doctype[^>]*?>)"); h = Clear(h, @"(]*?>)"); h = Clear(h, @"()"); h = Clear(h, @"()"); h = Clear(h, @"()"); h = Clear(h, @"(]*?>)"); h = Clear(h, @"()"); h = Clear(h, @"(]*?>)"); h = Clear(h, @"(\s*alt\s*=[""'\s]*[^>]*?['""]+)"); h = Clear(h, @"(\s*style\s*=[""'\s]*[^>]*?['""]+)"); h = Clear(h, @"(\s*title\s*=[""'\s]*[^>]*?['""]+)"); h = Clear(h, @"(\s*id\s*=[""'\s]*[^>]*?['""]+)"); h = Clear(h, @"(\s*class\s*=[""'\s]*[^>]*?['""]+)"); h = Clear(h, @"(\s*align\s*=[""'\s]*[^>]*?['""]+)"); h = h.Replace("\r\n", " "); h = h.Replace("\n", " ").Replace("\r", " ").Replace("\t", " "); h = h.Replace(" ", " "); h = h.Replace(" ", " "); h = h.Replace(" ", " "); h = h.Replace(" ", " "); return h.Replace(" ", " ").Replace(" ", " "); } /// /// 返回执行结果数 /// /// /// /// public static int GetRegexCount(string html, string regex) { if (html == null) { LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + regex); return 0; } return Regex.Matches(html, regex, RegexOptions.IgnoreCase).Count; } /// /// 根据正则删除表达式所匹配的内容 /// /// /// /// public static string Relpace(string HtmlString, string RegexString, string NewString) { if (HtmlString == null) return null; return Regex.Replace(HtmlString, RegexString, NewString, RegexOptions.IgnoreCase); } /// /// 根据正则删除表达式所匹配的内容 /// /// /// /// public static void Relpace(ref string HtmlString, string RegexString, string NewString) { if (HtmlString == null) return; HtmlString = Regex.Replace(HtmlString, RegexString, NewString, RegexOptions.IgnoreCase); } /// /// 关键词在文本中出现的次数 /// /// /// /// public static int GetStringCount(ref byte[] b, string keyword) { if (string.IsNullOrEmpty(keyword)) return 0; int c = 0; bool had; byte[] b1 = Encoding.UTF8.GetBytes(keyword); for (int i = 0; i < b.Length - b1.Length; i++) { had = false; for (int j = 0; j < b1.Length; j++) { if (b[i + j] != b1[j]) { had = true; break; } } if (had) { c++; i += b1.Length - 1; } } return c; } /// /// 是否存在 /// /// /// /// public static bool Exists(string html, string reg) { if (string.IsNullOrEmpty(html) || string.IsNullOrEmpty(reg)) return false; return new Regex(reg).IsMatch(html); } /// /// 是否是数字 /// /// /// public static bool IsNumber(string str) { System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[0-9\.]+$"); return reg1.IsMatch(str); } /// /// 是否是字母 /// /// /// public static bool IsChar(string str) { System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[A-Za-z]+$"); return reg1.IsMatch(str); } /// /// 是否是字母 /// /// /// public static bool IsCharOrNumber(string str) { System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[A-Za-z0-9]+$"); return reg1.IsMatch(str); } /// /// 是否是中文字符串列 /// /// /// public static bool IsWordList(string word) { char[] xj = word.ToCharArray(); for (int j = 0; j < xj.Length; j++) if (!IsWord(xj[j])) return false; return true; } /// /// 是否是字符 /// /// /// private static bool IsWord(int ascii) { if (ascii == 32 || ascii == 35) //空格 return true; if (ascii < 58 && ascii > 47) //数字 return true; if (ascii < 48 && ascii > 31) //符号 return true; if (ascii < 91 && ascii > 64) //小写字母 return true; if (ascii < 123 && ascii > 96) //大写字母 return true; if (ascii < 40892 && ascii > 13311) //中文字符串 return true; return false; } /// /// 获取值 /// /// /// /// public static bool GetBoolValue(string html, string reg) { string temp = GetMatchRegexString(html, "<" + reg + ">([^<]+)"); if (!string.IsNullOrEmpty(temp) && (temp.ToLower() == "true" || temp == "1")) return true; return false; } /// /// 获取值 /// /// /// /// public static int GetIntValue(string html, string reg) { string temp = GetMatchRegexString(html, "<" + reg + ">([^<]+)"); int i; if (int.TryParse(temp, out i)) return i; return 0; } /// /// 获取值 /// /// /// /// public static long GetLongValue(string html, string reg) { string temp = GetMatchRegexString(html, "<" + reg + ">([^<]+)"); long i; if (long.TryParse(temp, out i)) return i; return 0; } /// /// 获取值 /// /// /// /// public static double GetDoubleValue(string html, string reg) { string temp = GetMatchRegexString(html, "<" + reg + ">([^<]+)"); double i; if (double.TryParse(temp, out i)) return i; return 0; } /// /// 获取值 /// /// /// /// public static DateTime GetDateValue(string html, string reg) { string temp = GetMatchRegexString(html, "<" + reg + ">([^<]+)"); DateTime i; if (DateTime.TryParse(temp, out i)) return i; return DateTime.MinValue; } /// /// 获取值 /// /// /// /// public static decimal GetDecimalValue(string html, string reg) { string temp = GetMatchRegexString(html, "<" + reg + ">([^<]+)"); decimal i = 0; if (decimal.TryParse(temp, out i)) return i; return 0; } /// /// 获取值 /// /// /// /// public static decimal GetDecimalJson(ref string html, string reg) { string temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*['""]([^']+?)['""]"); if (string.IsNullOrEmpty(temp)) temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*([\d-\.]+)"); decimal i = 0; if (decimal.TryParse(temp, out i)) return i; return 0; } /// /// 获取值 /// /// /// /// public static decimal? GetNullableDecimalJson(ref string html, string reg) { string temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*['""]([^']+?)['""]"); if (string.IsNullOrEmpty(temp)) temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*([\d-\.]+)"); decimal i = 0; if (decimal.TryParse(temp, out i)) return i; return null; } /// /// 获取值 /// /// /// /// public static int GetIntJson(ref string html, string reg) { string temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*['""]([^']+?)['""]"); if (string.IsNullOrEmpty(temp)) temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*([\d-]+)"); int i; if (int.TryParse(temp, out i)) return i; return 0; } /// /// 获取值 /// /// /// /// public static int? GetNullableIntJson(ref string html, string reg) { string temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*['""]([^']+?)['""]"); if (string.IsNullOrEmpty(temp)) temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*([\d-]+)"); int i; if (int.TryParse(temp, out i)) return i; return null; } /// /// 获取值 /// /// /// /// public static bool GetBoolJson(ref string html, string reg) { var temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*(true|false)"); bool res; if (bool.TryParse(temp, out res)) return res; return false; } /// /// 获取值 /// /// /// /// public static bool? GetNullableBoolJson(ref string html, string reg) { var temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*(true|false)"); bool res; if (bool.TryParse(temp, out res)) return res; return null; } /// /// 时间戳转字符串时间 /// /// /// /// public static string GetIntTimeToString(ref string html, string reg) { return GetIntTimeToString(ref html, reg, 0); } /// /// 时间戳转字符串时间 /// /// /// /// 添加时间 /// public static string GetIntTimeToString(ref string html, string reg, int addTime) { int time = GetIntJson(ref html, reg) + addTime; DateTime dt = BaseClass.StampToDateTime(time); return dt.ToString("yyyy-MM-dd HH:mm:ss"); } /// /// 获取值 /// /// /// /// public static long GetLongJson(ref string html, string reg) { string temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*['""]([^']+?)['""]"); if (string.IsNullOrEmpty(temp)) temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*([\d]+)"); long i; if (long.TryParse(temp, out i)) return i; return 0; } /// /// 获取值 /// /// /// /// public static string GetStringJson(ref string html, string reg) { string temp = GetMatchRegexString(html, @"[""]" + reg + @"[""][\s]*:[\s]*[""]([^""]+?)[""]"); if (temp == null) temp = GetMatchRegexString(html, @"[""]" + reg + @"[""][\s]*:[\s]*[""]([^""]*?)[""]"); if (temp == null) temp = GetMatchRegexString(html, @"[']" + reg + @"['][\s]*:[\s]*[']([^']*?)[']"); if (temp == null) temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*([\d]+)"); return temp; } public static string GetOneJsonObjStrJson(ref string html, string reg) { return GetJsonObjStrJson(ref html, reg).FirstOrDefault(); } public static System.Collections.Generic.List GetJsonObjStrJson(ref string html, string reg, int level = 0) { System.Collections.Generic.List rstLst = new System.Collections.Generic.List(); if (html == null) return rstLst; string htmlTmp = html.Replace("\\{", "\\这里是正花括号占位符").Replace("\\}", "\\这里是反花括号占位符").Replace("\"" + reg + "\": {", "\"" + reg + "\":{"); retry: string lvStr = ""; if (level == 1) { lvStr += "\""; } var index1 = htmlTmp.IndexOf("\"" + reg + "\":" + lvStr + "{"); if (index1 < 0) return rstLst; htmlTmp = htmlTmp.Substring(index1 + ("\"" + reg + "\":" + lvStr + "{").Length - 1); // 括号计数 int braceNum = 0; //string rst = "{"; //while (htmlTmp.Length > 0) for (int i = 0; i < htmlTmp.Length; i++) { //rst += htmlTmp.Substring(0, 1); //if (htmlTmp.StartsWith("{")) // braceNum++; //else if (htmlTmp.StartsWith("}")) // braceNum--; if (htmlTmp[i] == '{') braceNum++; else if (htmlTmp[i] == '}') braceNum--; //htmlTmp = htmlTmp.Substring(1); if (braceNum == 0) { rstLst.Add(htmlTmp.Substring(0, i + 1).Replace("\\这里是正花括号占位符", "\\{").Replace("\\这里是反花括号占位符", "\\}")); htmlTmp = htmlTmp.Substring(i + 1); //rstLst.Add(rst.Replace("\\这里是正花括号占位符", "\\{").Replace("\\这里是反花括号占位符", "\\}")); break; } // 循环完了还没结果返回空列表 if (i == htmlTmp.Length - 1) return rstLst; } if (htmlTmp.Length > 0) goto retry; return rstLst; } public static System.Collections.Generic.List GetJsonArrStrJson(ref string html, string reg) { System.Collections.Generic.List rstLst = new System.Collections.Generic.List(); if (html == null) return rstLst; string htmlTmp = html.Replace("\\[", "\\这里是正方括号占位符").Replace("\\]", "\\这里是反方括号占位符").Replace("\"" + reg + "\": [", "\"" + reg + "\":["); retry: var index1 = htmlTmp.IndexOf("\"" + reg + "\":["); if (index1 < 0) return rstLst; htmlTmp = htmlTmp.Substring(index1 + ("\"" + reg + "\":[").Length); // 括号计数 int braceNum = 1; string rst = "["; while (htmlTmp.Length > 0) { rst += htmlTmp.Substring(0, 1); if (htmlTmp.StartsWith("[")) braceNum++; else if (htmlTmp.StartsWith("]")) braceNum--; htmlTmp = htmlTmp.Substring(1); if (braceNum == 0) { rstLst.Add(rst.Replace("\\这里是正方括号占位符", "\\[").Replace("\\这里是反方括号占位符", "\\]")); break; } } if (htmlTmp.Length > 0) goto retry; return rstLst; } /// /// 获取值 /// /// /// /// public static string GetStringInput(ref string html, string reg) { string temp = GetMatchRegexString(html, @"]*?name=['""]" + reg + @"[""'][^>]+?value=[""']([^>]+)[""'][^>]*>"); if (string.IsNullOrEmpty(temp)) temp = GetMatchRegexString(html, @"]*?value=[""']([^>]+)[""'][^>]+?name=['""]" + reg + @"[""'][^>]*>"); return temp; } /// /// 获取值 /// /// /// /// public static string GetStringQuery(ref string queryString, string key) { var queryStringTmp = "&" + queryString; int nIndex = queryStringTmp.IndexOf(key + "="); if (nIndex == -1) return null; string temp = queryStringTmp.Substring(nIndex).Replace(key + "=", ""); nIndex = temp.IndexOf('&'); if (nIndex > -1) temp = temp.Substring(0, nIndex); return temp; } /// /// 获取值 /// /// /// /// public static string GetStringCookie(ref string cookieStr, string key) { int nIndex = cookieStr.IndexOf(key + "="); if (nIndex == -1) return null; string temp = cookieStr.Substring(nIndex).Replace(key + "=", ""); nIndex = temp.IndexOf(';'); if (nIndex > -1) temp = temp.Substring(0, nIndex); return temp; } public static string FliterHtmlTag(string htmlStr) { if (String.IsNullOrEmpty(htmlStr)) { return ""; } string regEx_style = "]*?>[\\s\\S]*?<\\/style>"; //定义style的正则表达式 string regEx_script = "]*?>[\\s\\S]*?<\\/script>"; //定义script的正则表达式 string regEx_html = "<[^>]+>"; //定义HTML标签的正则表达式 htmlStr = Regex.Replace(htmlStr, regEx_style, "");//删除css htmlStr = Regex.Replace(htmlStr, regEx_script, "");//删除js htmlStr = Regex.Replace(htmlStr, regEx_html, "");//删除html标记 htmlStr = Regex.Replace(htmlStr, "\\s*|\t|\r|\n", "");//去除tab、空格、空行 htmlStr = htmlStr.Replace("\"", "");//去除异常的引号 return htmlStr.Trim(); } } }