----=== 字符串替换问题 ===----

kong19 2004-10-18 08:47:11
字符串很长,这是一部分 string a = "... G00 X-23.012 Y11.027 Z40.\r\nX-22.01Y18.I-1183.294J-2063.691\r\nX-26.353Y12.02\r\nG01X-26.353Y12.02F600\r\n ..."

我用正则表达式读取X的值后进行处理,如 -23.012+1 = -22.012 ; 再想把-22.012替换掉原来的-23.012怎么做,不能用a.replace(..),请帮帮忙阿
...全文
234 13 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
cyy1981 2004-10-18
  • 打赏
  • 举报
回复
upo
eradium 2004-10-18
  • 打赏
  • 举报
回复
ms-help://MS.MSDNQTR.2003FEB.2052/cpref/html/frlrfSystemTextRegularExpressionsRegexClassReplaceTopic.htm

那就用正则表达式的替换。
[C#]
using System.Text.RegularExpressions;

class RegExSample
{
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 + "]");
}
}
saucer 2004-10-18
  • 打赏
  • 举报
回复
try soemthing like


using System;
using System.Text.RegularExpressions;

class TestReg
{

static string MyEvaluator(Match m)
{
double d = Convert.ToDouble(m.Groups["num"].Value);
d += 1.0;
return m.Groups["pre"].Value + d.ToString();
}

static void Main()
{

string a = "... G00 X-23.012 Y11.027 Z40.\r\nX-22.01Y18.I-1183.294J-2063.691\r\nX-26.353Y12.02\r\nG01X-26.353Y12.02F600\r\n ...";

a = Regex.Replace(a, @"(?<pre>X)(?<num>[-]?\d+(\.\d*)?)", new MatchEvaluator(MyEvaluator));

//a = Regex.Replace(a, @"(?<pre>[A-Z])(?<num>[-]?\d+(\.\d*)?)", new MatchEvaluator(MyEvaluator));

Console.WriteLine(a);
}
}


kong19 2004-10-18
  • 打赏
  • 举报
回复
不行,那会把a 中所有的-23.012都变成-22.012,我只想把那个查到的x的值变化
kong19 2004-10-18
  • 打赏
  • 举报
回复
没有人会吗。。。。。。。
eradium 2004-10-18
  • 打赏
  • 举报
回复
a=a.replace("-23.012","-22.012");

string的replace函数是获得一个替换后的副本,不会改变原来的string的。
kong19 2004-10-18
  • 打赏
  • 举报
回复
分可以再加,up也有分
tkss 2004-10-18
  • 打赏
  • 举报
回复
mazekui 2004-10-18
  • 打赏
  • 举报
回复
up
3850 2004-10-18
  • 打赏
  • 举报
回复
up
kong19 2004-10-18
  • 打赏
  • 举报
回复
是不是用正则表达式可以替换掉原来的值啊
Regex regx=new Regex("x *(?<ab>[0-9.-]+)",RegexOptions.IgnoreCase|RegexOptions.Multiline);
MatchCollection xmatchesFound=regx.Matches(a);
GroupCollection xmatchGroups;

string x = null;
foreach(Match xmatch in xmatchesFound)
{
//..
}
kong19 2004-10-18
  • 打赏
  • 举报
回复
我用的正则表达式
Regex("x *(?<ab>[0-9.-]+)",RegexOptions.IgnoreCase|RegexOptions.Multiline)
kong19 2004-10-18
  • 打赏
  • 举报
回复
up先

111,092

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧