首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

用正则类怎么替换查找出来的字符

2012-01-24 
用正则类如何替换查找出来的字符?那个属性是只读的无法替换?[解决办法]用委托string test aaaa{1}dddd

用正则类如何替换查找出来的字符?
那个属性是只读的无法替换?

[解决办法]
用委托

string test = "aaaa{=1=}dddd{=0=}cccc{=31=} ";
string result = Regex.Replace(test, @ "\{=(\d+)=\} ", new MatchEvaluator(regReplace));


private string regReplace(Match m)
{
switch (m.Groups[1].Value)
{
case "1 ":
return "abc ";
case "0 ":
return "ccc ";
}
return " ";
}
[解决办法]
private void button1_Click(object sender, EventArgs e)
{
string s = "1 12 3 5 ";
s = Regex.Replace(s, @ "\d+ ", new MatchEvaluator(CorrectString), RegexOptions.Compiled | RegexOptions.IgnoreCase);
txtView.Text = s;
}

private static string CorrectString(Match match)
{
string matchValue = match.Value;
if (matchValue.Length == 1)
matchValue = "0 " + matchValue;
return matchValue;
}

结果是 01 12 03 05

热点排行