正则表达式替换和获取:CS1056意外字符'$'

时间:2017-05-20 21:44:13

标签: c# regex

我正在尝试将html代码转换为bbcode,我发现这个漂亮的小类充满了正则表达式。

 public static string ConvertBBCodeToHTML(string str)
    {
        Regex exp;
        // format the bold tags: [b][/b]
        // becomes: <strong></strong>
        exp = new Regex(@"[b](.+?)[/b]");
        str = exp.Replace(str, "<strong>$1</strong>");

        // format the italic tags: [i][/i]
        // becomes: <em></em>
        exp = new Regex(@"[i](.+?)[/i]");
        str = exp.Replace(str, "<em>$1</em>");

        // format the underline tags: [u][/u]
        // becomes: <u></u>
        exp = new Regex(@"[u](.+?)[/u]");
        str = exp.Replace(str, "<u>$1</u>");

        // format the strike tags: [s][/s]
        // becomes: <strike></strike>
        exp = new Regex(@"[s](.+?)[/s]");
        str = exp.Replace(str, "<strike>$1</strike>");

        // format the url tags: [url=www.website.com]my site[/url]
        // becomes: <a href="www.website.com">my site[/url]
        exp = new Regex(@"[url=([^]]+)]([^]]+)[/url]");
        str = exp.Replace(str, "<a href="$1">$2[/url]");

        // format the img tags:  
        // becomes: <img src="www.website.com/img/image.jpeg">
        exp = new Regex(@"[img]([^]]+)[/img]");
        str = exp.Replace(str, "<img src="$1">");

        // format img tags with alt: [img=www.website.com/img/image.jpeg]this is the alt text[/img]
        // becomes: <img src="www.website.com/img/image.jpeg" alt="this is the alt text">
        exp = new Regex(@"[img=([^]]+)]([^]]+)[/img]");
        str = exp.Replace(str, "<img src="$1" alt="$2">");

        //format the colour tags: [color=red][/color]
        // becomes: <font color="red"></font>
        // supports UK English and US English spelling of colour/color
        exp = new Regex(@"[color=([^]]+)]([^]]+)[/color]");
        str = exp.Replace(str, "<font color="$1">$2</font>");
        exp = new Regex(@"[colour=([^]]+)]([^]]+)[/colour]");
        str = exp.Replace(str, "<font color="$1">$2</font>");

        // format the size tags: [size=3][/size]
        // becomes: <font size="+3"></font>
        exp = new Regex(@"[size=([^]]+)]([^]]+)[/size]");
        str = exp.Replace(str, "<font size=" +$1">$2</font>");

        // lastly, replace any new line characters with 

        str = str.Replace("rn", "rn");

        return str;
    }

问题是我在进行正则表达式替换时遇到CS1056 Unexpected character '$'错误,即使它看起来完全有效。

2 个答案:

答案 0 :(得分:0)

您需要在以下字符串中转义嵌入式双引号"

"<a href="$1">$2[/url]"

他们应该是:

"<a href=\"$1\">$2[/url]"

verbatim string literals

@"<a href=""$1"">$2[/url]"

答案 1 :(得分:0)

您应该使用单引号在字符串中嵌入值,如下所示:

exp = new Regex(@"[url=([^]]+)]([^]]+)[/url]");
str = exp.Replace(str, "<a href='$1'>$2[/url]");