gpt4 book ai didi

c# - 替换为 .Replace/.Regex

转载 作者:行者123 更新时间:2023-11-30 16:28:50 27 4
gpt4 key购买 nike

我正在使用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com