逻辑解析给定字符串中的特定html标记并构建不同类型字符串的集合

时间:2014-01-11 10:13:40

标签: c# string logic

我想为下面的场景编写一个逻辑,需要关于它的最佳实现的想法 -

  1. 我有3种类型的文字。 Type1: - High,Type2:Medium,Type3:Low
  2. 我在HTML中用不同的方式表示这些文本中的每一个 - 如下所示   对于类型1: - 高 - > Html看起来像这样

      

    < font color = Red>< b> Sample High Text< / b>< / font>

    表示类型2: - 中 - > Html看起来像这样

      

    < font color = Blue>< u> Sample Medium Text>< / u>< / font>

    对于类型3,

    : - 低 - >没有Html,它的纯文本

      

    示例低文本

  3. 所以我有这样的结果字符串 -

      

    < font color = Red>< b> Sample High Text< / b>< / font>样本低文本>< font color = Blue>< u>样本媒体文字>< / u>< / font>

  4. 我想构建一个包含文本及其类型的集合
  5. 结果字符串只包含上面提到的html,其他html就不存在了。

    请为此逻辑建议良好的方法。

1 个答案:

答案 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));
    }
}