正则表达式,用于从字符串中删除特定的BBCode [英] Regex for removing a specific BBCode from a string

查看:55
本文介绍了正则表达式,用于从字符串中删除特定的BBCode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一种简单的方法来从输入字符串中删除特定的BBCodes.

I'm trying to write a simple method for removing specific BBCodes from an input string.

例如,我输入以下内容:

For example, where I have an input of:

string input = "[b]Hello World![/b]";

我希望能够做到:

Remove(input, "b");

并获得以下输出:

"Hello World!"

Regex确实不是我的强项.我设法从Google整理了以下内容:

Regex really isn't my strong suit. I've managed to piece together the following from google:

public static string Remove(string input, string code)
{
    string pattern = string.Format(@"\[{0}\].*?\[\/{1}\]", code, code);

    return Regex.Replace(input, pattern, string.Empty, RegexOptions.IgnoreCase);
}

不幸的是,对于我给定的示例,这将返回一个空字符串.

Unfortunately this returns an empty string for my given example.

有人可以建议我如何纠正我的正则表达式以获取所需的输出吗?

Can anyone advise me on how I can correct my regex to get the desired output?

谢谢

推荐答案

使用以下简单的正则表达式: \ [/?{0} \]

Use this simple regex: \[/?{0}\]

您的正则表达式将删除整个字符串

  • 您的正则表达式 \ [{0} \].*?\ [\/{1} \] 正在删除整个 [b] ... [/b] 字符串.这就是为什么从替换中得到空字符串的原因.

  • Your regex \[{0}\].*?\[\/{1}\] is removing the entire [b]...[/b] string. That's why you are getting an empty string from the replacement.

您需要删除的只是 [b] [b] .在常规正则表达式中,这很容易用 \ [/?b \] 表示,其中斜杠由?

What you need is to remove only the [b] and [b]. In normal regex, this is expressed quite simply with \[/?b\], where the slash is made optional by the ?

在参数化的正则表达式中,类似 \ [/?{0} \] 的东西将起作用.

In your parametrized regex, something like \[/?{0}\] will work.

这篇关于正则表达式,用于从字符串中删除特定的BBCode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆