替换字符串中间的值

本文关键字:中间 字符串 替换 | 更新日期: 2023-09-27 18:03:37

以下代码说明:

  • 我正在加载一个。txt文件,并创建一个列表来存储它。
  • while循环将所有文本存储到列表中。
  • 我创建了3个列表来存储不同的值。
  • 我使用REGEX来匹配看起来像"111.111"的数字。
  • 如果在行中匹配,将其分组为"X"answers"Y"。
  • 将每个分组项目添加到上面创建的新列表中(其中3个)。
  • 使用TextBox输入值对"X"answers"Y"值进行加法。
  • 输出StringBuilder值到RichTextBoxes

    private void calculateXAndYPlacement()
    {s
        // Reads the lines in the file to format.
        var fileReader = File.OpenText(filePath + "''Calculating X,Y File.txt");
        // Creates a list for the lines to be stored in.
        var fileList = new List<string>();
        // Adds each line in the file to the list.
        var fileLines = "";                                       #UPDATED @Corey Ogburn
        while ((fileLines = fileReader.ReadLine()) != null)       #UPDATED @Corey Ogburn
            fileList.Add(fileLines);                              #UPDATED @Corey Ogburn
        // Creates new lists to hold certain matches for each list.
        var xyResult = new List<string>();
        var xResult = new List<string>();
        var yResult = new List<string>();
        // Iterate over each line in the file and extract the x and y values
        fileList.ForEach(line =>
        {
            Match xyMatch = Regex.Match(line, @"(?<x>-?'d+'.'d+)'s+(?<y>-?'d+'.'d+)");
            if (xyMatch.Success)
            {
                // Grab the x and y values from the regular expression match
                String xValue = xyMatch.Groups["x"].Value;
                String yValue = xyMatch.Groups["y"].Value;
                // Add these two values, separated by a space, to the "xyResult" list.
                xyResult.Add(String.Join(" ", new[]{ xValue, yValue }));
                // Add the results to the lists.
                xResult.Add(xValue);
                yResult.Add(yValue);
                // Calculate the X & Y values (including the x & y displacements)
                double doubleX = double.Parse(xValue);
                double doubleXValue = double.Parse(xDisplacementTextBox.Text);
                StringBuilder sbX = new StringBuilder();
                sbX.AppendLine((doubleX + doubleXValue).ToString());
                double doubleY = double.Parse(yValue);
                double doubleYValue = double.Parse(yDisplacementTextBox.Text);
                StringBuilder sbY = new StringBuilder();
                sbY.AppendLine((doubleY + doubleYValue).ToString());
                calculatedXRichTextBox.AppendText(sbX + "'n");
                calculatedYRichTextBox.AppendText(sbY + "'n");
            }
        });
    }
    

NOW::: 我要做的是采取这些新值是在calculatedXRichTextBoxcalculatedYRichTextBox替换旧值(在fileList)并输出它们以覆盖calculatedXRichTextBoxcalculatedYRichTextBox

所以,我的值是:

(原始文件)

TEXT   TEXT  227.905  203.244  180  
TEXT   TEXT  242.210  181.294  180  
TEXT   TEXT  236.135  198.644  90  

(剥夺了值"X"answers"Y"—— 2 不同的列表)

227.905                      203.244  
242.210                      181.294  
236.135                      198.644  

(将"10"加到"X"answers"20"加到"Y"的计算值—将它们放入2不同的RichTextBoxes)

237.905                      223.244
252.210                      201.294
246.135                      218.644

(这就是我想要结束的——原始文件+计算值替换旧值)

TEXT   TEXT  237.905  223.244  180  
TEXT   TEXT  252.210  201.294  180  
TEXT   TEXT  246.135  218.644  90  

问题:

  • 我该怎么做?

替换字符串中间的值

解决问题的另一种方法是将代码视为对数据流应用转换。

这基本上就是下面的示例所做的。它是为。net 4.0编写的,如果你的目标是更早的运行时,你将不得不使用ReadAllLines方法(而不是ReadLines),而不是使用Tuple,你需要制作一个容器类(可以是该类的私有)从你的函数返回多个值。

void calculateXAndYPlacement()
{
    // Read data from file
    var path = @"[path to your document]";
    var data = File.ReadLines(path + "data.txt");
    // Parse the values you'll be modifying your data by
    var doubleXValue = double.Parse(xDisplacementTextBox.Text);
    var doubleYValue = double.Parse(yDisplacementTextBox.Text);                     
    // apply your transformation to all valid lines of data
    var modifiedData = from line in data
                       where LineIsValid( line )
                       select ModifyLine( line, doubleXValue, doubleYValue );
    // Do what you wish with the data
    foreach( var dataPoint in modifiedData )
    {
         // grab the values from the Tuple and put them into the
         // appropriate text boxes.
    }
}
Tuple<string,double,double> ModifyLine(string data, double xValue, double yValue)
{
    // split line into parts
    var columns = Regex.Split(data, @"'s+");
    columns.Dump();
    // do your math on each part, I just assigned the new values
    // for the sake of the example.
    columns[3] = xValue.ToString();
    columns[4] = yValue.ToString();
    // recombine the line
    return Tuple.Create( string.Join(" ", columns), xValue, yValue );
}
bool LineIsValid(string lineData)
{
    return Regex.IsMatch(lineData, @"(?<x>-?'d+'.'d+)'s+(?<y>-?'d+'.'d+)");
}

既然你已经在使用正则表达式来匹配你的值,为什么不尝试使用正则表达式呢?

查看此链接获取更多信息

http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.replace (v = vs.71) . aspx

尝试字符串。像下面这样替换伪代码:

int i=0;
while(newline){
   if(patternMatch){
      // replace old values with new ones
      line.Replace(oldXList[i], newXList[i]).Replace(oldYList[i], newYList[i]);
      i++;
   }
}

它不是很优雅,但应该可以工作,对吗?