标签:
public void ShowStructure()
{
//要匹配的字符串
string text = "1A 2B 3C 4D 5E 6F 7G 8H 9I 10J 11Q 12J 13K 14L 15M 16N ffee80 #800080";
//正则表达式
string pattern = @"((\d+)([a-z]))\s+";
//使用RegexOptions.IgnoreCase枚举值表示不区分大小写
Regex r = new Regex(pattern, RegexOptions.IgnoreCase);
//使用正则表达式匹配字符串,仅返回一次匹配结果
Match m = r.Match(text);
while (m.Success)
{
System.Console.WriteLine("Match=[" + m + "]");
CaptureCollection cc = m.Captures;
foreach (Capture c in cc)
{
Console.WriteLine("\tCapture=[" + c + "]");
}
for (int i = 0; i < m.Groups.Count; i++)
{
Group group = m.Groups[i];
System.Console.WriteLine("\t\tGroups[{0}]=[{1}]", i, group);
for (int j = 0; j < group.Captures.Count; j++)
{
Capture capture = group.Captures[j];
Console.WriteLine("\t\t\tCaptures[{0}]=[{1}]", j, capture);
}
}
//进行下一次匹配.
m = m.NextMatch();
}
}
public void Matches()
{
//要匹配的字符串
string text = "1A 2B 3C 4D 5E 6F 7G 8H 9I 10J 11Q 12J 13K 14L 15M 16N ffee80 #800080";
//正则表达式
string pattern = @"((\d+)([a-z]))\s+";
//使用RegexOptions.IgnoreCase枚举值表示不区分大小写
Regex r = new Regex(pattern, RegexOptions.IgnoreCase);
//使用正则表达式匹配字符串,返回所有的匹配结果
MatchCollection matchCollection = r.Matches(text);
foreach (Match m in matchCollection)
{
//显示匹配开始处的索引值和匹配到的值
System.Console.WriteLine("Match=[" + m + "]");
CaptureCollection cc = m.Captures;
foreach (Capture c in cc)
{
Console.WriteLine("\tCapture=[" + c + "]");
}
for (int i = 0; i < m.Groups.Count; i++)
{
Group group = m.Groups[i];
System.Console.WriteLine("\t\tGroups[{0}]=[{1}]", i, group);
for (int j = 0; j < group.Captures.Count; j++)
{
Capture capture = group.Captures[j];
Console.WriteLine("\t\t\tCaptures[{0}]=[{1}]", j, capture);
}
}
}
}
public void UBBDemo()
{
string text = "[url=http://zhoufoxcn.blog.51cto.com][/url][url=http://blog.csdn.net/zhoufoxcn]周公的专栏[/url]";
Console.WriteLine("原始UBB代码:" + text);
Regex regex = new Regex(@"(\[url=([ \S\t]*?)\])([^[]*)(\[\/url\])", RegexOptions.IgnoreCase);
MatchCollection matchCollection = regex.Matches(text);
foreach (Match match in matchCollection)
{
string linkText = string.Empty;
//如果包含了链接文字,如第二个UBB代码中存在链接名称,则直接使用链接名称
if (!string.IsNullOrEmpty(match.Groups[3].Value))
{
linkText = match.Groups[3].Value;
}
else//否则使用链接作为链接名称
{
linkText = match.Groups[2].Value;
}
text = text.Replace(match.Groups[0].Value, "<a href=\"" + match.Groups[2].Value + "\" target=\"_blank\">" + linkText + "</a>");
}
Console.WriteLine("替换后的代码:"+text);
本文出自 “周公(周金桥)的专栏” 博客,请务必保留此出处http://zhoufoxcn.blog.51cto.com/792419/281956
标签:
原文地址:http://www.cnblogs.com/Jacklovely/p/5605882.html