天天看點

C#中使用正規表達式比對字元串

<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 &lt; 5) ? Index : 5; </b>

<b>18.                int fromEnd = str.Length - Index - result.Length; </b>

<b>19.                int charsAfter = (fromEnd &lt; 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>