编程语言
首页 > 编程语言> > c#-替换为.Replace / .Regex

c#-替换为.Replace / .Regex

作者:互联网

我正在使用Html.Raw(Html.Encode())允许某些html被允许.例如,我想要粗体,斜体,代码等…我不确定这是正确的方法,代码看起来非常丑陋.

输入项

Hello, this text will be [b]bold[/b]. [code]alert(“Test…”)[/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>"))

我的解决方案

我想让一切变得不同.我不想使用BB标签,而是使用更简单的标签,例如*代表粗体.这意味着如果我输入此文本为*粗体*.它将替换为.此文本为< b&b bold< / b>.类似此网站的Kinda正在使用BTW.

问题

要实现此功能,我需要一些Regex,而我对此几乎没有经验.我搜索了许多站点,但是没有运气.

我的实现看起来像这样,但是由于我不能真正用字符串替换char而失败.

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

解决方法:

To implement this I need some Regex

啊,不,您不需要Regex.使用Regex操纵HTML可能会导致大约undesired effects.因此,您可以简单地使用MarkDownSharp,这是该网站用来安全地将Markdown标记呈现为HTML的方式.

像这样:

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

当然,要完善这一点,您可以编写一个HTML帮助器,以便您认为:

@Html.Markdown(Model.Body)

标签:c,regex,asp-net-mvc-3
来源: https://codeday.me/bug/20191208/2089120.html