namespace com.softwee.smgw.common { using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text.RegularExpressions; public abstract class RegexHelper { protected RegexHelper() { } public static List ToRegExpressions(string source) { List list = new List(); Regex regex = new Regex(@"(\(.*?\|.*?\)|\*+)|^(\(.*?\|.*?\)|\*+)", RegexOptions.IgnoreCase); Regex regex2 = new Regex(@"[\[\]\}\{\.\-\,\^]", RegexOptions.IgnoreCase); foreach (string str in source.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)) { try { string input = regex2.Replace(str, m => @"\" + m.Value); string str3 = regex.Replace(input, delegate(Match m) { if (!m.Value.StartsWith("(") && m.Value.StartsWith("*")) { return @"[\w\W]{0," + (m.Value.Length * 10) + "}?"; } return m.Value; }); list.Add(new Regex(str3 + "$")); } catch (Exception) { } } return list; } public static bool ValidateRegex(string source, out string errorString) { List list = new List(); errorString = string.Empty; Regex regex = new Regex(@"(\(.*?\|.*?\)|\*+)|^(\(.*?\|.*?\)|\*+)", RegexOptions.IgnoreCase); Regex regex2 = new Regex(@"[\[\]\}\{\.\-\,\?\+\^]", RegexOptions.IgnoreCase); foreach (string str in source.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)) { try { string input = regex2.Replace(str, m => @"\" + m.Value); string pattern = regex.Replace(input, delegate(Match m) { if (!m.Value.StartsWith("(") && m.Value.StartsWith("*")) { return @"[\w\W]{0," + (m.Value.Length * 10) + "}?"; } return m.Value; }); list.Add(new Regex(pattern)); } catch (Exception exception) { errorString = errorString + exception.Message + "\n"; } } if (errorString.Length > 100) { errorString = errorString.Substring(0, 100) + "……"; } return string.IsNullOrEmpty(errorString); } } }