Regex 101 Exercise I7 - Make sure all characters inside <> are uppercase
Posted on 2006-02-07 23:03 Sheva 阅读(1527) 评论(3) 编辑 收藏 举报
In this exercise, Eric asks us to replace all html tag names with uppercase equivalent. My answer is based on Maurits' suggestion, that is to say using MatchEvaluator.
MatchEvaluator enables you to perform custom verification and manipulation for each single match found by the Regex.Replace method, probably I'm just too pedantic about it, okay, here comes the code:
MatchEvaluator enables you to perform custom verification and manipulation for each single match found by the Regex.Replace method, probably I'm just too pedantic about it, okay, here comes the code:
using System;
using System.Text.RegularExpressions;
namespace RegexExerciseI7
{
class Program
{
static void Main(String[] args)
{
Regex regex = new Regex(@"<(?<slash>/?)(?<tag>[^>]+)>", RegexOptions.IgnoreCase);
Console.WriteLine("Type in the HTML text you want to process:");
String inputHtml = Console.ReadLine();
String resultHtml = regex.Replace(inputHtml, delegate(Match match)
{
String slash = match.Groups["slash"].Value;
String tag = match.Groups["tag"].Value.ToUpperInvariant();
return String.Equals(slash, "/") ? String.Format("</{0}>", tag) : String.Format("<{0}>", tag);
});
Console.WriteLine(resultHtml);
}
}
}
In this code snippet, you will find that I perform an extra check to make sure that all the starting tags(e.g <html>) and ending tags(e.g </html>) will be considered.using System.Text.RegularExpressions;
namespace RegexExerciseI7
{
class Program
{
static void Main(String[] args)
{
Regex regex = new Regex(@"<(?<slash>/?)(?<tag>[^>]+)>", RegexOptions.IgnoreCase);
Console.WriteLine("Type in the HTML text you want to process:");
String inputHtml = Console.ReadLine();
String resultHtml = regex.Replace(inputHtml, delegate(Match match)
{
String slash = match.Groups["slash"].Value;
String tag = match.Groups["tag"].Value.ToUpperInvariant();
return String.Equals(slash, "/") ? String.Format("</{0}>", tag) : String.Format("<{0}>", tag);
});
Console.WriteLine(resultHtml);
}
}
}