Regex for removing a specific BBCode from a string

核能气质少年 提交于 2019-12-02 01:03:40

问题


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]";

I would want to be able to do:

Remove(input, "b");

And get an output of:

"Hello World!"

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?

Thanks


回答1:


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

Your regex is removing the whole string

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

  • 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 ?

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




回答2:


The below regex would capture the string Hello World! inside the second group.

^(.*?)((?<=])[^[]*)(.*)$

DEMO

So replace all your input string with the second captured group.




回答3:


If you sure that both starting and trailing special symbol must occur and you don't want them to be in a result, you can use positive look back ((?<=(your symbols here))) and positive look ahead ((?=(your symbols here))) for specified characters.

Complete answer will look like this:

(?<=(\[{0}\])).*(?=(\[\/{1}\]))


来源:https://stackoverflow.com/questions/24428460/regex-for-removing-a-specific-bbcode-from-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!