如何使用正则表达式中的变量$ 1在方法C#中使用?

时间:2013-12-28 11:54:47

标签: c# regex

我有以下代码,但我有1美元是错的,我不知道:

// [size=4]Size[/size]
sText = Regex.Replace(sText, @"/\[size=([1-7])\]((\s|.)+?)\[\/size\]/i", "<span style='font-size: "+ GetCssSizeByFontSize($1) +";'></span>");

我想以某种方式使用正则表达式中的$1来在我的函数GetCssSizeByFontSize中使用

private static string GetCssSizeByFontSize(string fontSize)
        {
            switch (fontSize)
            {
                case "1":
                    return "xx-small";
                case "2":
                    return "x-small";
                case "3":
                    return "small";
                default:
                case "4":
                    return "medium";
                case "5":
                    return "large";
                case "6":
                    return "x-large";
                case "7":
                    return "xx-large";
            }
        }

我想使用我的函数将[size=4]Some text[/size]替换为<span style='font-size: medium;'>Some text</span>

如何使用正则表达式来实现这一目标?

1 个答案:

答案 0 :(得分:0)

首先,您不使用/个字符来界定C#中的正则表达式模式,因此您的模式应如下所示:

(?i)\[size=([1-7])\]((\s|.)+?)\[\/size\]

但这可以简化为:

(?i)\[size=([1-7])](.+?)\[/size]

其次,您可以将MatchEvaluator委托传递给replace方法。这可以是lambda表达式,如下所示:

sText = Regex.Replace(sText, 
    @"(?i)\[size=([1-7])](.+?)\[/size]", 
    m => "<span style='font-size: "+ GetCssSizeByFontSize(m.Groups[1].Value) +";'></span>");