1,C#正则表达式Match类和Group类用法 将上面的UBB编码转换成HTML代码:
///
/// 下面的代码实现将文本中的UBB超级链接代码替换为HTML超级链接代码
///
public void UBBDemo()
{
string text = "[url=http://zhoufoxcn.blog.51cto.com][/url][url=http://blog.youkuaiyun.com/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, "" + linkText + "");
}
Console.WriteLine("替换后的代码:"+text);
}
2,匹配出字符串中需要的内容
string text = "<td class=\"jrj-tc\">2013-08-08</td><td class=\"jrj-tr\">1.2155</td><td class=\"jrj-tr\">4.516%</td>";
text += "<tr class='cur'><td class=\"jrj-tc\">2013-08-07</td><td class=\"jrj-tr\">1.2118</td><td class=\"jrj-tr\">4.509%</td></tr>";
string regStr = @"\<td class=""jrj-tc""\>(\d{4}-\d{2}-\d{2})</td><td class=""jrj-tr"">(.+?)</td><td class=""jrj-tr"">(.+?)</td>";
Regex regex = new Regex(regStr, RegexOptions.IgnoreCase);
MatchCollection matchCollection = regex.Matches(text);
foreach (Match match in matchCollection)
{
Console.WriteLine("1:"+match.Groups[1].Value);
Console.WriteLine("2:" + match.Groups[2].Value);
Console.WriteLine("3:" + match.Groups[3].Value);
Console.WriteLine();
}
结果:1:2013-08-08
2:1.2155
3:4.516%
1:2013-08-07
2:1.2118
3:4.509%