[英]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: 我有以下代码,但是我有$ 1的地方不对,我不知道:
// [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
我想以某种方式使用正则表达式中的$1
在名为GetCssSizeByFontSize
函数中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. 我想用我的函数将[size=4]Some text[/size]
替换为<span style='font-size: medium;'>Some text</span>
。
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: 首先,您不使用/
字符来分隔C#中的正则表达式模式,因此您的模式应如下所示:
(?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. 其次,您可以将MatchEvaluator
委托传递给replace方法。 This can be a lambda expression, like this: 这可以是lambda表达式,如下所示:
sText = Regex.Replace(sText,
@"(?i)\[size=([1-7])](.+?)\[/size]",
m => "<span style='font-size: "+ GetCssSizeByFontSize(m.Groups[1].Value) +";'></span>");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.