c# - 替换为 .Replace/.Regex

标签 c# regex asp.net-mvc-3

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

输入

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

输出

enter image description here

代码

    @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 标签,而是使用更简单的标签。
例如 *将代表粗体。这意味着如果我输入 This text is *bold*.它会将文本替换为 This text is <b>bold</b>. .有点像这个网站正在使用顺便说一句。

问题

要实现这一点,我需要一些正则表达式,但我对此几乎没有经验。我搜索了很多网站,但没有成功。

我的实现看起来像这样,但它失败了,因为我无法真正替换 charstring .

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 操作 HTML 可能会导致一些 undesired effects .所以你可以简单地使用 MarkDownSharp顺便说一下,这是本网站用来安全呈现 Markdown 的工具标记为 HTML。

像这样:

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

当然,为了完善这一点,您可以编写一个 HTML 帮助程序,以便在您看来:

@Html.Markdown(Model.Body)

关于c# - 替换为 .Replace/.Regex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6829720/

相关文章:

unit-testing - 没有字符串的单元测试 MVC3 Razor 助手/ View

c# - 如何使用.net youtube API直接上传获取上传状态

c# - GL 项目无法正常工作

javascript - 如何从页面源代码中使用正则表达式获取&lt;script&gt;代码?

javascript - JS - 检查字符串是否只包含 0

c# - Excel XML 电子表格 CSHTML

c# - ASP.NET 5 Beta 7 (Web Tools 2015 Beta7) - wwwroot/index.html 未提供

键入时来自 SQL Server 的 C# 文本框值

java - 在逗号后面的空格后找不到正确的正则表达式来拆分

asp.net-mvc - 如何在编辑器模板中使用传递的选择列表