Replace返回相同值的2
本文关键字:返回 Replace | 更新日期: 2023-09-27 18:04:06
我有一个问题,为什么会发生这种情况。首先,我将解释发生了什么。我在RichTextBox
中找到一条线,并取Split
值,并用相同的值替换它,但有十进制限制。下面是我的文件的样子:
J6 INT-00113G 227.905 174.994 180 SOIC8
J3 INT-00113G 227.905 203.244 180 SOIC8
U13 EXCLUDES 242.210 181.294 180 QFP128
但是出于某种原因,当我试图替换并输出它时,我得到了这个…(数字在第三列和第四列同时出现两次)
J6 INT-00113G 227.91227.91 174.99174.99 180 SOIC8
J3 INT-00113G 227.91227.91 203.24203.24 180 SOIC8
U13 EXCLUDES 242.21242.21 181.29181.29 180 QFP128
这是我的代码…使它这样做的错误是什么?
string[] myLines = placementTwoRichTextBox.Text.Split(''n');
foreach (string line in myLines)
{
// Matches the entire line.
Match theMatch = Regex.Match(line, @".*");
if (theMatch.Success)
{
// Stores the matched value in string output.
string output = theMatch.Value;
// Replaces tabs and extra space with only 1 space delimiter
output = Regex.Replace(output, @"'s+", " ");
// Splits the specified regex into two different regexs.
var componentItem = output.Split(' ');
double d1 = Convert.ToDouble(componentItem[2]);
double d2 = Convert.ToDouble(componentItem[3]);
double round1 = Math.Round(d1, 2, MidpointRounding.AwayFromZero);
double round2 = Math.Round(d2, 2, MidpointRounding.AwayFromZero);
componentItem[2] = Regex.Replace(componentItem[2], @".*", round1.ToString());
componentItem[3] = Regex.Replace(componentItem[3], @".*", round2.ToString());
// Sets the RichTextBox to the string output.
newPl2ItemsRichTextBox.AppendText(componentItem[0] + " " + componentItem[1] + " " + componentItem[2] +
" " + componentItem[3] + " " + componentItem[4] + " " + componentItem[5] + "'n");
}
}
有人知道为什么会这样吗?
不做这些,只做你的分割,因为你知道索引2和3包含你的数字…简单地执行如下操作:
newPl2ItemsRichTextBox。AppendText(componentItem[0] + " " + componentItem[1] + " " + Math.Round(Convert.ToDouble(componentItem[2]), 2) + " " + Math.Round(Convert.ToDouble(componentItem[3]), 2) + " " + componentItem[4] + " " + componentItem[5] + "'n");
避免所有其他步骤,只需要分割并打印。
您的表达式"。*"命中两根火柴:试着复制下面的代码:
static void Main(string[] args)
{
Regex regex = new Regex(@".*");
MatchCollection matches = regex.Matches(" 227.905 ");
foreach (var match in matches)
{
Console.WriteLine("[{0}]", match);
}
Console.ReadKey();
}
匹配:"227.905"answers"
回答你的问题:在227.905中,中间有一个点可能让替换函数在227和905上工作。这就是为什么四舍五入的数字被插入两次。