Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace with .Replace/.Regex

I am using Html.Raw(Html.Encode()) to allow some of html to be allowed. For example I want bold, italic, code etc... I am not sure it's the right method, code seems pretty ugly.

Input

Hello, this text will be [b]bold[/b]. [code]alert("Test...")[/code]

Output

enter image description here

Code

    @Html.Raw(Html.Encode(Model.Body)
    .Replace(Environment.NewLine, "<br />")
    .Replace("[b]", "<b>")
    .Replace("[/b]", "</b>")
    .Replace("[code]", "<div class='codeContainer'><pre name='code' class='javascript'>")
    .Replace("[/code]", "</pre></div>"))

My Solution

I want to make it all a bit different. Instead of using BB-Tags I want to use simpler tags.
For example * will stand for bold. That means if I input This text is *bold*. it will replace text to This text is <b>bold</b>.. Kinda like this website is using BTW.

Problem

To implement this I need some Regex and I have little to no experience with it. I've searched many sites, but no luck.

My implementation of it looks something like this, but it fails since I can't really replace a char with string.

static void Main(string[] args)
{
    string myString = "Hello, this text is *bold*, this text is also *bold*. And this is code: ~MYCODE~";
    string findString = "\\*";
    int firstMatch, nextMatch;

    Match match = Regex.Match(myString, findString);

    while (match.Success == true)
    {
        Console.WriteLine(match.Index);
        firstMatch = match.Index;
        match = match.NextMatch();
        if (match.Success == true)
        {
            nextMatch = match.Index;

            myString = myString[firstMatch] = "<b>"; // Ouch!
        }
    }

    Console.ReadLine();
}
like image 905
Stan Avatar asked May 25 '26 01:05

Stan


1 Answers

To implement this I need some Regex

Ah no, you don't need Regex. Manipulating HTML with Regex could lead to some undesired effects. So you could simply use MarkDownSharp which by the way is what this site uses to safely render Markdown markup into HTML.

Like this:

var markdown = new Markdown();
string html = markdown.Transform(SomeTextContainingMarkDown);

Of course to polish this you would write an HTML helper so that in your view:

@Html.Markdown(Model.Body)
like image 187
Darin Dimitrov Avatar answered May 26 '26 13:05

Darin Dimitrov