本文实例报告了C#正则函数用法。分享给人人供人人参考,细致以下:
System.Text.RegularExpressions 定名空间包括一些类,这些类供应对 .NET Framework 正则表达式引擎的接见。该定名空间供应正则表达式功用,能够从运行在 Microsoft .NET Framework 内的任何平台或言语中运用该功用。
1 正则表达式的罕见运用
① 花样婚配
/// <summary> /// 邮箱花样考证 /// </summary> /// <returns></returns> public static string CheckMail(string strEmail) { string result = ""; Regex regex = new Regex(@"[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}"); Match match = regex.Match(strEmail); if(match.Success) { result = strEmail; } else { result = "无效邮箱"; } return result; }
② 替代婚配内容
/// <summary> /// 转换日期花样(yyyy-MM-dd 转 yyyy年MM月dd日) /// </summary> /// <param name="strDate"></param> /// <returns></returns> public static string TransDate(string strDate) { string result = ""; Regex regex = new Regex(@"(\d+)-(\d+)-(\d+)"); if(regex.IsMatch(strDate)) { result = regex.Replace(strDate,"$1年$2月$3日"); } return result; }
③ 提取婚配内容
/// <summary> /// 正则表达式提取和替代内容 /// </summary> public static string Contentextract() { string result = ""; string str = "人人好! <User EntryTime='2010-10-7' Email='zhangsan@163.com'>张三</User> 毛遂自荐。"; Regex regex = new Regex(@"<User\s*EntryTime='(?<time>[\s\S]*?)'\s+Email='(?<email>[\s\S]*?)'>(?<userName>[\s\S]*?)</User>", RegexOptions.IgnoreCase); Match match = regex.Match(str); if(match.Success) { string userName = match.Groups["userName"].Value; //猎取用户名 string time = match.Groups["time"].Value; //猎取入职时候 string email = match.Groups["email"].Value; //猎取邮箱地址 string strFormat = String.Format("我是:{0},入职时候:{1},邮箱:{2}", userName, time, email); result = regex.Replace(str, strFormat); //替代内容 Console.WriteLine(result); } return result; //效果:人人好!我是张三,入职时候:2010-10-7,邮箱:zhangsan@163.com 毛遂自荐。 }
2 我的一个实例
/// <summary> /// 从XML中提取婚配的字段 /// </summary> /// <param name="args"></param> static void Main(string[] args) { string strXml = GetStrXml(); //建立用户信息XML Regex userRegex = new Regex(@"<User\s*EntryTime='(?<time>[\s\S]*?)'\s+Email='(?<email>[\s\S]*?)'>(?<userName>[\s\S]*?)</User>", RegexOptions.IgnoreCase); MatchCollection userMatchColl = userRegex.Matches(strXml); if (userMatchColl.Count > 0) { foreach (Match matchItem in userMatchColl) { string userName = matchItem.Groups["userName"].Value; //猎取用户名 string time = TransDate(matchItem.Groups["time"].Value); //猎取入职时候,并转换日期花样 string email = CheckMail(matchItem.Groups["email"].Value); //猎取邮箱地址,并检测邮箱花样 string strFormat = String.Format("姓名:{0},入职时候:{1},邮箱:{2}", userName, time, email); Console.WriteLine(strFormat); } } Console.ReadLine(); } /// <summary> /// 建立用户信息XML /// </summary> /// <returns></returns> public static string GetStrXml() { StringBuilder strXml = new StringBuilder(); strXml.Append("<UserInfo>"); strXml.Append("<User EntryTime='2010-10-7' Email='zhangsan@163.com'>张三</User>"); strXml.Append("<User EntryTime='2012-5-15' Email='lisi163.com'>李四</User>"); strXml.Append("<User EntryTime='2012-6-13' Email='wangwu@qq.com'>王五</User>"); strXml.Append("</UserInfo>"); return strXml.ToString(); }
以上就是C#正则函数婚配、替代、提取的用法代码分享的细致内容,更多请关注ki4网别的相干文章!