有些时候我偶们希望在正则表达式的替换中对替换的字符换进行简单的处理,比如把所有的A依次替换为B1、B2、B3……这就需在替换时对字符串进行处理,其实这个很简单,用C#中的MatchEvaluator委托就可以了。简单的示例如下:

private static int i = 0;

public static string ParseToHTML(string ubbString)
{
Regex rgx;
string htmlString = "";

MatchEvaluator me = new MatchEvaluator(AddOne);
rgx = new Regex(@"\[code\](.*?)\[\/code\]");
htmlString = rgx.Replace(htmlString, me);

return htmlString;
}

public static string AddOne(Match m)
{
string code = m.Value.Substring(6, m.Value.Length - 13);
string codeString = @"<textarea class="code_text" name="code" + i + "">" + code + "</textarea>";
i++;
return codeString;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.