c# 正則表達式 匹配中括號&顏色過濾


現在需要匹配 [color=#000000],以"[color"開頭,以"[/color]"結束,中間字符數量不限制,最后返回所有匹配的下標。

代碼如下:

 1         /// <summary>         
 2         /// 取得所有匹配項
 3         /// </summary>         
 4         /// <param name="source">原內容</param>         
 5         /// <returns>返回匹配列表的下標</returns>         
 6         public static int[] GetColorIndexGroup(string source)
 7         {
 8             // 定義正則表達式用來匹配  
 9             Regex reg = new Regex("\\[color.*?\\].*?\\[/color\\]", RegexOptions.IgnoreCase);
10 
11             //將匹配到的項替換為空
12             //var newSource = reg.Replace(source, "");
13 
14             // 搜索匹配的字符串             
15             MatchCollection matches = reg.Matches(source);
16 
17             int i = 0;
18             //存放下標
19             int[] colorIndexGroup = new int[matches.Count];
20             //存放匹配到的內容
21             string[] colorContentGroup = new string[matches.Count];
22 
23             // 取得匹配項列表             
24             foreach (Match match in matches)
25             {
26                 colorContentGroup[i] = match.Value;
27                 colorIndexGroup[i++] = match.Index;
28             }
29             return colorIndexGroup;
30         }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM