简体   繁体   中英

How to use variable $1 from regex to be used in a method C#?

I have the following code but where I have $1 is wrong, I don't know:

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

I want to use somehow $1 from regex to be used in my function called 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";
            }
        }

I want to replace [size=4]Some text[/size] with <span style='font-size: medium;'>Some text</span> using my function.

How to achieve this using regex ?

First, you don't use / characters to delimit regular expression patterns in C#, so your pattern should look like this:

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

But this can simplified to:

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

Second, you can pass a MatchEvaluator delegate to the replace method. This can be a lambda expression, like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM