坐标,X123,Y234,Z345
替换成
坐标,X12.3,Y15.6,Z345即 找到 "坐标,.*Y[0-9]" 将"[0-9]" 这个数字处理后替换
比如Y234加减乘除运算后替换为Y15.6Regex.Replace(s, @"坐标,.*Y[0-9]", "xxx");//这样肯定不行,请教虾虾们
替换成
坐标,X12.3,Y15.6,Z345即 找到 "坐标,.*Y[0-9]" 将"[0-9]" 这个数字处理后替换
比如Y234加减乘除运算后替换为Y15.6Regex.Replace(s, @"坐标,.*Y[0-9]", "xxx");//这样肯定不行,请教虾虾们
public string System.Text.RegularExpressions.Regex.Replace (
string input,
MatchEvaluator evaluator
)替换在 Regex 构造函数中指定的正则表达式所定义的字符模式的所有匹配项。在每个匹配处均调用 MatchEvaluator 委托以计算替换。参数input
要修改的字符串。 evaluator
在每一步计算替换的 MatchEvaluator。 返回值
已修改的字符串。 备注MatchEvaluator 类型是采用单个 Match 作为输入并返回字符串的委托。其声明如下所示: public delegate String RegexMatchEvaluator(Match match); 在替换过程中为每个匹配项调用一次委托。
{
static string CapText(Match m)
{
// Get the matched string.
string x = m.ToString();
// If the first char is lower case...
if (char.IsLower(x[0]))
{
// Capitalize it.
return char.ToUpper(x[0]) + x.Substring(1, x.Length-1);
}
return x;
}
static void Main()
{
string text = "four score and seven years ago";
System.Console.WriteLine("text=[" + text + "]");
string result = Regex.Replace(text, @"\w+",
new MatchEvaluator(RegExSample.CapText));
System.Console.WriteLine("result=[" + result + "]");
}
}
{
static string XYZ(Match m)
{
string s = m.ToString();
decimal d;
if (decimal.TryParse(s.Substring(2), out d))
{
switch (s[1])
{
case 'X': return string.Format(",{0}{1}", s[1], d / 10);
case 'Y': return string.Format(",{0}{1}", s[1], d / 15);
case 'Z': return string.Format(",{0}{1}", s[1], d * 1 );
default : return s;
}
}
return s;
}
static void Main()
{
string text = "坐标,X123,Y234,Z345";
string patt = ",[XYZ][0-9]+";
string result = Regex.Replace(text, patt, new MatchEvaluator(XYZ));
System.Console.WriteLine("替换前=[" + text + "]");
System.Console.WriteLine("替换后=[" + result + "]");
}
}
/*程序输出:
替换前=[坐标,X123,Y234,Z345]
替换后=[坐标,X12.3,Y15.6,Z345]
*/
{
// 这样,xyz统一处理,计算新的xyz值时可以用旧的xyz的任何值。
static string XYZ(Match m)
{
try
{
decimal x = decimal.Parse(m.Groups[1].Value);
decimal y = decimal.Parse(m.Groups[2].Value);
decimal z = decimal.Parse(m.Groups[3].Value);
return string.Format("坐标,X{0},Y{1},Z{2}", x/10, y/15, (x+y+z)/3+111);
}
catch (System.FormatException)
{
return m.ToString();
}
}
static void Main()
{
string text = "坐标,X123,Y234,Z345";
string patt = "(?i)坐标,x([0-9]+),y([0-9]+),z([0-9]+)";
string result = Regex.Replace(text, patt, new MatchEvaluator(XYZ));
System.Console.WriteLine("替换前=[" + text + "]");
System.Console.WriteLine("替换后=[" + result + "]");
}
}
/*
程序输出:
替换前=[坐标,X123,Y234,Z345]
替换后=[坐标,X12.3,Y15.6,Z345]
*/
wuyi8808
空军
的帮助我要的是
return string.Format("坐标,X{0},Y{1},Z{2}", x/10, y*2, z/3+111);
这样的效果就行了不好意思我没说清楚, 让你费脑子了,:) 辛苦了 !