您的位置:首页 > 编程语言 > C#

c# 正则表达式 匹配中括号&颜色过滤

2016-08-28 13:24 921 查看
现在需要匹配 [color=#000000],以"[color"开头,以"[/color]"结束,中间字符数量不限制,最后返回所有匹配的下标。

代码如下:

/// <summary>
/// 取得所有匹配项
/// </summary>
/// <param name="source">原内容</param>
/// <returns>返回匹配列表的下标</returns>
public static int[] GetColorIndexGroup(string source)
{
// 定义正则表达式用来匹配
Regex reg = new Regex("\\[color.*?\\].*?\\[/color\\]", RegexOptions.IgnoreCase);

//将匹配到的项替换为空
//var newSource = reg.Replace(source, "");

// 搜索匹配的字符串
MatchCollection matches = reg.Matches(source);

int i = 0;
//存放下标
int[] colorIndexGroup = new int[matches.Count];
//存放匹配到的内容
string[] colorContentGroup = new string[matches.Count];

// 取得匹配项列表
foreach (Match match in matches)
{
colorContentGroup[i] = match.Value;
colorIndexGroup[i++] = match.Index;
}
return colorIndexGroup;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: