Kawyllainy Vi Kawyllainy Vi - 3 months ago 16
C# Question

Extract and Transform

How can I accomplish the task of extracting text within tags and transform them ?

Example:

out formatted

input:

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


Out:
This is italic
Bold Text

I'm using this code to extract the text between the tags , but the problem is that it only takes the text of the first tag

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);

}


What I would like to accomplish and exactly what happens in stackoverflow Editor ...

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

richTextBox1.AppendText("Bold Text");

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

richTextBox1.AppendText("Normal Text");


To bold text use ****
and italic **

Answer

Here's a way of doing what I think you need:

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*)\](.*)\[\/\1\]");

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

And this is the result if you use a standard RichTextBox:

End result in RichTextBox control

Of course this is just a starting point. If you want to combine formats or any other feature, you will have to add that. ;)

Comments