<b>C#中使用正则表达式匹配字符串的方法如下:</b>
1.使用System.Text.RegularExpressions命名空间;
2.使用Matches()方法匹配字符串,格式如下:
MatchCollection Matches = Regex.Matches(Str, Pattern, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
其中Str表示输入字符串,Pattern表示匹配模式,RegexOptions.IgnoreCase表示忽略大小写,RegexOptions.ExplicitCapture表示改变收集匹配方式。
3.匹配结果保存在MatchCollection集合中,可以通过循环遍历结果集取出Match对象的结果。
TestRagular.cs:
<b>01.using System; </b>
<b>02.using System.Text.RegularExpressions; </b>
<b>03. </b>
<b>04.namespace Magci.Test.Strings </b>
<b>05.{ </b>
<b>06. public class TestRegular </b>
<b>07. { </b>
<b>08. public static void WriteMatches(string str, MatchCollection matches) </b>
<b>09. { </b>
<b>10. Console.WriteLine("\nString is : " + str); </b>
<b>11. Console.WriteLine("No. of matches : " + matches.Count); </b>
<b>12. foreach (Match nextMatch in matches) </b>
<b>13. { </b>
<b>14. //取出匹配字符串和最多10个外围字符 </b>
<b>15. int Index = nextMatch.Index; </b>
<b>16. string result = nextMatch.ToString(); </b>
<b>17. int charsBefore = (Index < 5) ? Index : 5; </b>
<b>18. int fromEnd = str.Length - Index - result.Length; </b>
<b>19. int charsAfter = (fromEnd < 5) ? fromEnd : 5; </b>
<b>20. int charsToDisplay = charsBefore + result.Length + charsAfter; </b>
<b>21. </b>
<b>22. Console.WriteLine("Index: {0},\tString: {1},\t{2}", Index, result, str.Substring(Index - charsBefore, charsToDisplay)); </b>
<b>23. } </b>
<b>24. } </b>
<b>25. </b>
<b>26. public static void Main() </b>
<b>27. { </b>
<b>28. string Str = @"My name is Magci, for short mgc. I like c sharp!"; </b>
<b>29. </b>
<b>30. //查找“gc” </b>
<b>31. string Pattern = "gc"; </b>
<b>32. MatchCollection Matches = Regex.Matches(Str, Pattern, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture); </b>
<b>33. </b>
<b>34. WriteMatches(Str, Matches); </b>
<b>35. </b>
<b>36. //查找以“m”开头,“c”结尾的单词 </b>
<b>37. Pattern = @"\bm\S*c\b"; </b>
<b>38. Matches = Regex.Matches(Str, Pattern, RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture); </b>
<b>39. </b>
<b>40. WriteMatches(Str, Matches); </b>
<b>41. } </b>
<b>42. } </b>
<b>43.}</b>
<b></b>
<b> 本文转自My_King1 51CTO博客,原文链接:</b><b>http://blog.51cto.com/apprentice/1360721</b><b>,如需转载请自行联系原作者</b>