我想为下面的场景编写一个逻辑,需要关于它的最佳实现的想法 -
我在HTML中用不同的方式表示这些文本中的每一个 - 如下所示 对于类型1: - 高 - > Html看起来像这样
< font color = Red>< b> Sample High Text< / b>< / font>
表示类型2: - 中 - > Html看起来像这样
对于类型3,< font color = Blue>< u> Sample Medium Text>< / u>< / font>
: - 低 - >没有Html,它的纯文本
示例低文本
所以我有这样的结果字符串 -
< font color = Red>< b> Sample High Text< / b>< / font>样本低文本>< font color = Blue>< u>样本媒体文字>< / u>< / font>
结果字符串只包含上面提到的html,其他html就不存在了。
请为此逻辑建议良好的方法。
答案 0 :(得分:2)
您应该将输入行拆分为单独的文本块,然后确定每个文本块的类型:
enum TextType
{
High,
Medium,
Low
}
class Program
{
static void Main(string[] args)
{
var html = "<font color=Red><b>Sample High Text</b></font>Sample Low Text<font color=Blue><u>Sample Medium Text</u></font>";
var rawStrings = System.Text.RegularExpressions.Regex.Split(html, "(?=<font)|(</font>)");
var nonEmptyRawStrings = rawStrings.Select(s => System.Text.RegularExpressions.Regex.Replace(s, "</font>|</u>|</b>", ""))
.Where(s => !String.IsNullOrEmpty(s))
.ToList();
const string highPrefix = "<font color=Red><b>";
const string mediumPrefix = "<font color=Blue><u>";
var typedString = nonEmptyRawStrings.Select(s => new
{
Type = s.StartsWith(highPrefix) ? TextType.High : (s.StartsWith(mediumPrefix) ? TextType.Medium : TextType.Low),
String = s.Replace(highPrefix, "").Replace(mediumPrefix, "")
}).ToList();
typedString.ForEach(s => Console.WriteLine("Type: {0}\tString: {1}", s.Type, s.String));
}
}