提取和转换

Extract and Transform

如何完成提取标签中的文本并对其进行转换的任务?

示例:

out formatted

输入:

[txtItalic]This is italic[/txtItalic] [txtBold] Bold Text [/txtBold]

输出: 这是斜体 粗体文本

我正在使用这段代码提取标签之间的文本,但问题是它只提取第一个标签的文本

string ExtractString(string s, string tag)
{
    var startTag = "[" + tag + "]";
    int startIndex = s.IndexOf(startTag) + startTag.Length;
    int endIndex = s.IndexOf("[/" + tag + "]", startIndex);
    return s.Substring(startIndex, endIndex - startIndex);

}

我想完成什么以及在 Whosebug 编辑器中究竟发生了什么...

         richTextBox1.SelectionFont = new Font(richTextBox1.Font, FontStyle.Bold);

        richTextBox1.AppendText("Bold Text");

        richTextBox1.SelectionFont = new Font(richTextBox1.Font, FontStyle.Regular);

        richTextBox1.AppendText("Normal Text");

要加粗文本,请使用 **** 和斜体 **

这应该可以为您完成工作:

string s = "[txtItalic]This is italic[/txtItalic] [txtBold] Bold Text [/txtBold]";
//creating a list of tags
List<string> tags = new List<string>();
tags.Add("txtItalic");
tags.Add("txtBold");
//iterating through each of the tags
foreach (string tag in tags)
{
    var startTag = "[" + tag + "]";
    int startIndex = s.IndexOf(startTag) + startTag.Length;
    int endIndex = s.IndexOf("[/" + tag + "]", startIndex);
    string s1 = s.Substring(startIndex, endIndex - startIndex);
    Console.Write(s1);
}

输出:

This is italic Bold Text

注意:这只会提取标签之间的文本。

这是我认为您需要的方法:

private void YourMethod()
{
    Process("[txtItalic]This is italic[/txtItalic], this is normal, [txtBold]Bold Text[/txtBold] and now [txtUnderline]Underlined Text[/txtUnderline]. The end.");
}

private void Process(string textWithTags)
{
    MatchCollection matches = Regex.Matches(textWithTags, @"\[(\w*)\](.*)\[\/\]");

    int unformattedStartPosition = 0;
    int unformattedEndPosition = 0;
    foreach (Match item in matches)
    {
        unformattedEndPosition = textWithTags.IndexOf(item.Value);

        // Add unformatted text.
        AddText(textWithTags.Substring(unformattedStartPosition, unformattedEndPosition - unformattedStartPosition), FontStyle.Regular);

        // Add formatted text.
        FontStyle style = GetStyle(item.Groups[1]);
        AddText(item.Groups[2].Value, style);

        unformattedStartPosition = unformattedEndPosition + item.Value.Length;
    }

    AddText(textWithTags.Substring(unformattedStartPosition), FontStyle.Regular);
}

private FontStyle GetStyle(Group group)
{
    switch (group.Value)
    {
        case "txtItalic":
            return FontStyle.Italic;
        case "txtBold":
            return FontStyle.Bold;
        case "txtUnderline":
            return FontStyle.Underline;
        default:
            return FontStyle.Regular;
    }
}

private void AddText(string text, FontStyle style)
{
    if (text.Length == 0)
        return;

    richTextBox.SelectionFont = new Font(richTextBox.SelectionFont, style);
    richTextBox.AppendText(text);
}

如果您使用标准的 RichTextBox,这就是结果:

当然这只是一个起点。如果您想组合格式或任何其他功能,则必须添加它。 ;)