公司展示类网站模板免费下载,网站建设桔子科技,免费电商网站模板,机械加工完工单C# 正则表达式完全指南 
C#通过 System.Text.RegularExpressions 命名空间提供强大的正则表达式支持。本指南将详细介绍C#中正则表达式的使用方法、性能优化和最佳实践。 
1. 基础知识 
1.1 命名空间导入 
using System.Text.RegularExpressions;1.2 基本使用 
public class Re…C# 正则表达式完全指南 
C#通过 System.Text.RegularExpressions 命名空间提供强大的正则表达式支持。本指南将详细介绍C#中正则表达式的使用方法、性能优化和最佳实践。 
1. 基础知识 
1.1 命名空间导入 
using System.Text.RegularExpressions;1.2 基本使用 
public class RegexBasics
{public void BasicExamples(){string text  Hello, my phone is 123-456-7890;// 创建正则表达式对象Regex regex  new Regex(\d);// 检查是否匹配bool isMatch  regex.IsMatch(text);// 查找第一个匹配Match match  regex.Match(text);if (match.Success){Console.WriteLine($Found: {match.Value});}// 查找所有匹配MatchCollection matches  regex.Matches(text);foreach (Match m in matches){Console.WriteLine($Found: {m.Value});}}
}1.3 正则表达式选项 
public class RegexOptions
{public void OptionsExample(){// 不区分大小写Regex caseInsensitive  new Regex(hello, RegexOptions.IgnoreCase);// 多行模式Regex multiline  new Regex(^start, RegexOptions.Multiline);// 忽略空白字符和注释Regex ignored  new Regex(\d  # 匹配数字\s*  # 可选的空白字符\w  # 匹配单词, RegexOptions.IgnorePatternWhitespace);// 编译正则表达式以提高性能Regex compiled  new Regex(\d, RegexOptions.Compiled);}
}2. 正则表达式语法 
2.1 字符匹配 
public class CharacterMatching
{public void MatchingExamples(){string text  C# 10.0 is awesome! Price: $99.99;// 匹配数字Regex digits  new Regex(\d);foreach (Match m in digits.Matches(text)){Console.WriteLine($Number: {m.Value});}// 匹配单词Regex words  new Regex(\w);var wordMatches  words.Matches(text).CastMatch().Select(m  m.Value).ToList();// 匹配空白字符string[] parts  Regex.Split(text, \s);// 自定义字符类Regex vowels  new Regex([aeiou], RegexOptions.IgnoreCase);var vowelMatches  vowels.Matches(text).CastMatch().Select(m  m.Value).ToList();}
}2.2 分组和捕获 
public class GroupingExample
{public void GroupExamples(){string text  John Smith, Jane Doe, Bob Johnson;// 基本分组Regex regex  new Regex((\w)\s(\w));foreach (Match match in regex.Matches(text)){Console.WriteLine($Full name: {match.Groups[0].Value});Console.WriteLine($First name: {match.Groups[1].Value});Console.WriteLine($Last name: {match.Groups[2].Value});}// 命名分组Regex namedRegex  new Regex((?first\w)\s(?last\w));foreach (Match match in namedRegex.Matches(text)){Console.WriteLine($First: {match.Groups[first].Value});Console.WriteLine($Last: {match.Groups[last].Value});}}
}3. 高级特性 
3.1 替换操作 
public class ReplacementOperations
{public string ReplaceExample(string text){// 简单替换string result1  Regex.Replace(text, \d, X);// 使用MatchEvaluator委托string result2  Regex.Replace(text, \d, match {int number  int.Parse(match.Value);return (number * 2).ToString();});// 使用命名组的替换Regex regex  new Regex((?first\w)\s(?last\w));string result3  regex.Replace(text, ${last}, ${first});return result3;}
}3.2 前瞻和后顾 
public class LookAroundExample
{public void LookAroundDemo(){string text  Price: $100, Cost: $50;// 正向前瞻Regex positiveAhead  new Regex(\d(?\s*dollars));// 负向前瞻Regex negativeAhead  new Regex(\d(?!\s*dollars));// 正向后顾Regex positiveBehind  new Regex((?\$)\d);// 负向后顾Regex negativeBehind  new Regex((?!\$)\d);}
}4. 实用工具类 
4.1 验证器 
public class Validator
{private static readonly Regex EmailRegex  new Regex(^[a-zA-Z0-9._%-][a-zA-Z0-9.-]\.[a-zA-Z]{2,}$,RegexOptions.Compiled);private static readonly Regex PhoneRegex  new Regex(^1[3-9]\d{9}$,RegexOptions.Compiled);private static readonly Regex PasswordRegex  new Regex(^(?.*[A-Za-z])(?.*\d)[A-Za-z\d]{8,}$,RegexOptions.Compiled);public static bool IsValidEmail(string email){if (string.IsNullOrEmpty(email)) return false;return EmailRegex.IsMatch(email);}public static bool IsValidPhone(string phone){if (string.IsNullOrEmpty(phone)) return false;return PhoneRegex.IsMatch(phone);}public static bool IsValidPassword(string password){if (string.IsNullOrEmpty(password)) return false;return PasswordRegex.IsMatch(password);}
}4.2 文本处理器 
public class TextProcessor
{private static readonly Regex UrlRegex  new Regex(https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))[^\s]*,RegexOptions.Compiled);private static readonly Regex HtmlTagRegex  new Regex([^],RegexOptions.Compiled);public static IEnumerablestring ExtractUrls(string text){if (string.IsNullOrEmpty(text)) return Enumerable.Emptystring();return UrlRegex.Matches(text).CastMatch().Select(m  m.Value);}public static string StripHtmlTags(string html){if (string.IsNullOrEmpty(html)) return string.Empty;return HtmlTagRegex.Replace(html, string.Empty);}public static string CleanWhitespace(string text){if (string.IsNullOrEmpty(text)) return string.Empty;return Regex.Replace(text.Trim(), \s,  );}
}5. 性能优化 
5.1 静态编译正则表达式 
public class RegexOptimization
{// 使用静态字段存储编译后的正则表达式private static readonly Regex CompiledRegex  new Regex(\d,RegexOptions.Compiled);// 使用LazyT延迟初始化private static readonly LazyRegex LazyRegex  new LazyRegex(()  new Regex(\d, RegexOptions.Compiled));public void OptimizedExample(){// 使用编译后的正则表达式bool isMatch  CompiledRegex.IsMatch(123);// 使用延迟初始化的正则表达式bool lazyMatch  LazyRegex.Value.IsMatch(123);}
}5.2 性能考虑 
public class PerformanceConsiderations
{// 1. 使用适当的选项private static readonly Regex FastRegex  new Regex(\d,RegexOptions.Compiled | RegexOptions.ExplicitCapture);// 2. 避免过度使用通配符private static readonly Regex BetterRegex  new Regex([^/]*foo[^/]*,  // 比 .*foo.* 更高效RegexOptions.Compiled);// 3. 使用非捕获组private static readonly Regex NonCapturingRegex  new Regex((?:\d)(?:[a-z]),  // 使用(?:)表示非捕获组RegexOptions.Compiled);
}6. 异常处理 
public class RegexExceptionHandling
{public static Regex CreateSafeRegex(string pattern){try{return new Regex(pattern, RegexOptions.Compiled);}catch (ArgumentException ex){throw new ArgumentException($Invalid regex pattern: {ex.Message}, ex);}}public static bool SafeIsMatch(string input, string pattern){try{return Regex.IsMatch(input, pattern);}catch (RegexMatchTimeoutException ex){Console.WriteLine($Regex matching timed out: {ex.Message});return false;}catch (ArgumentException ex){Console.WriteLine($Invalid regex pattern: {ex.Message});return false;}}
}7. 单元测试 
[TestClass]
public class ValidatorTests
{[TestMethod]public void TestEmailValidation(){Assert.IsTrue(Validator.IsValidEmail(testexample.com));Assert.IsTrue(Validator.IsValidEmail(userdomain.co.uk));Assert.IsFalse(Validator.IsValidEmail(invalid.email));Assert.IsFalse(Validator.IsValidEmail(domain.com));}[TestMethod]public void TestPhoneValidation(){Assert.IsTrue(Validator.IsValidPhone(13812345678));Assert.IsFalse(Validator.IsValidPhone(12345678));Assert.IsFalse(Validator.IsValidPhone(2381234567));}[TestMethod]public void TestTextProcessing(){string html  pHello/pdivWorld/div;Assert.AreEqual(HelloWorld,TextProcessor.StripHtmlTags(html));string text    multiple   spaces   here  ;Assert.AreEqual(multiple spaces here,TextProcessor.CleanWhitespace(text));}
}总结 
C#的正则表达式实现具有以下特点 
强大的Regex类支持编译选项提供高性能LINQ集成完整的Unicode支持 
最佳实践 
使用静态编译的Regex对象提高性能合理使用RegexOptions处理超时和异常情况编写完整的单元测试使用命名捕获组提高可读性 
注意事项 
Regex对象创建开销大应该重用考虑使用Compiled选项提高性能处理RegexMatchTimeoutException注意内存使用 
记住在C#中使用正则表达式时要充分利用.NET框架提供的功能如编译选项和LINQ集成。合理使用静态编译和缓存可以显著提高性能。 文章转载自: http://www.morning.qkxnw.cn.gov.cn.qkxnw.cn http://www.morning.dkqbc.cn.gov.cn.dkqbc.cn http://www.morning.ctswj.cn.gov.cn.ctswj.cn http://www.morning.taojava.cn.gov.cn.taojava.cn http://www.morning.tmcmj.cn.gov.cn.tmcmj.cn http://www.morning.hgbzc.cn.gov.cn.hgbzc.cn http://www.morning.slysg.cn.gov.cn.slysg.cn http://www.morning.jbtlf.cn.gov.cn.jbtlf.cn http://www.morning.plfy.cn.gov.cn.plfy.cn http://www.morning.dtnjr.cn.gov.cn.dtnjr.cn http://www.morning.dygsz.cn.gov.cn.dygsz.cn http://www.morning.dmtld.cn.gov.cn.dmtld.cn http://www.morning.znqmh.cn.gov.cn.znqmh.cn http://www.morning.knqzd.cn.gov.cn.knqzd.cn http://www.morning.dgmjm.cn.gov.cn.dgmjm.cn http://www.morning.rpth.cn.gov.cn.rpth.cn http://www.morning.ffksr.cn.gov.cn.ffksr.cn http://www.morning.czcbl.cn.gov.cn.czcbl.cn http://www.morning.mwjwy.cn.gov.cn.mwjwy.cn http://www.morning.fhxrb.cn.gov.cn.fhxrb.cn http://www.morning.zsgbt.cn.gov.cn.zsgbt.cn http://www.morning.rdnkx.cn.gov.cn.rdnkx.cn http://www.morning.bwzzt.cn.gov.cn.bwzzt.cn http://www.morning.pswzc.cn.gov.cn.pswzc.cn http://www.morning.bfjyp.cn.gov.cn.bfjyp.cn http://www.morning.zrkws.cn.gov.cn.zrkws.cn http://www.morning.trplf.cn.gov.cn.trplf.cn http://www.morning.gllhx.cn.gov.cn.gllhx.cn http://www.morning.jqswf.cn.gov.cn.jqswf.cn http://www.morning.hmsong.com.gov.cn.hmsong.com http://www.morning.dyfmh.cn.gov.cn.dyfmh.cn http://www.morning.grryh.cn.gov.cn.grryh.cn http://www.morning.flpjy.cn.gov.cn.flpjy.cn http://www.morning.npfrj.cn.gov.cn.npfrj.cn http://www.morning.wspyb.cn.gov.cn.wspyb.cn http://www.morning.fndfn.cn.gov.cn.fndfn.cn http://www.morning.pcbfl.cn.gov.cn.pcbfl.cn http://www.morning.zlxkp.cn.gov.cn.zlxkp.cn http://www.morning.mmjyk.cn.gov.cn.mmjyk.cn http://www.morning.jwgnn.cn.gov.cn.jwgnn.cn http://www.morning.fldsb.cn.gov.cn.fldsb.cn http://www.morning.cpmfp.cn.gov.cn.cpmfp.cn http://www.morning.jbgzy.cn.gov.cn.jbgzy.cn http://www.morning.srzhm.cn.gov.cn.srzhm.cn http://www.morning.dsxgc.cn.gov.cn.dsxgc.cn http://www.morning.trqsm.cn.gov.cn.trqsm.cn http://www.morning.wnpps.cn.gov.cn.wnpps.cn http://www.morning.krtcjc.cn.gov.cn.krtcjc.cn http://www.morning.fmswb.cn.gov.cn.fmswb.cn http://www.morning.rhdln.cn.gov.cn.rhdln.cn http://www.morning.qnqt.cn.gov.cn.qnqt.cn http://www.morning.smxrx.cn.gov.cn.smxrx.cn http://www.morning.kzcz.cn.gov.cn.kzcz.cn http://www.morning.bnbtp.cn.gov.cn.bnbtp.cn http://www.morning.tpnch.cn.gov.cn.tpnch.cn http://www.morning.pflpb.cn.gov.cn.pflpb.cn http://www.morning.nlcw.cn.gov.cn.nlcw.cn http://www.morning.gkjnz.cn.gov.cn.gkjnz.cn http://www.morning.fbxdp.cn.gov.cn.fbxdp.cn http://www.morning.xllrf.cn.gov.cn.xllrf.cn http://www.morning.rpdmj.cn.gov.cn.rpdmj.cn http://www.morning.sqskm.cn.gov.cn.sqskm.cn http://www.morning.qfgwx.cn.gov.cn.qfgwx.cn http://www.morning.mjmtm.cn.gov.cn.mjmtm.cn http://www.morning.geledi.com.gov.cn.geledi.com http://www.morning.dkfb.cn.gov.cn.dkfb.cn http://www.morning.aishuxue.com.cn.gov.cn.aishuxue.com.cn http://www.morning.nzkc.cn.gov.cn.nzkc.cn http://www.morning.jtcq.cn.gov.cn.jtcq.cn http://www.morning.dsncg.cn.gov.cn.dsncg.cn http://www.morning.fdwlg.cn.gov.cn.fdwlg.cn http://www.morning.txqsm.cn.gov.cn.txqsm.cn http://www.morning.pqqxc.cn.gov.cn.pqqxc.cn http://www.morning.gqjzp.cn.gov.cn.gqjzp.cn http://www.morning.lfdzr.cn.gov.cn.lfdzr.cn http://www.morning.fxqjz.cn.gov.cn.fxqjz.cn http://www.morning.fnwny.cn.gov.cn.fnwny.cn http://www.morning.ydzly.cn.gov.cn.ydzly.cn http://www.morning.xqgfy.cn.gov.cn.xqgfy.cn http://www.morning.zhnpj.cn.gov.cn.zhnpj.cn