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         }
原文地址:https://www.cnblogs.com/zhangtingzu/p/5814818.html