【问题标题】:Replacing values mid-string替换字符串中间的值
【发布时间】:2011-10-14 10:20:57
【问题描述】:

以下代码说明:

  • 我正在加载一个 .txt 文件并创建一个列表来存储它。
  • while 循环将所有文本存储到列表中。
  • 我再创建 3 个列表来存储不同的值。
  • 我使用 REGEX 来匹配看起来像“111.111”的数字。
  • 如果是匹配的行,将其分组为“X”和“Y”。
  • 将每个分组的项目添加到上面创建的新列表(其中 3 个)中。
  • 使用TextBox 输入值对“X”和“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 中的这些新值并 替换 strong> 旧值(在文件列表中) 并输出它们以覆盖calculatedXRichTextBoxcalculatedYRichTextBox

所以,我的价值观是:

(原始文件)

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

(剥离值“X”和“Y”——在 2 个不同的列表中)

227.905                      203.244  
242.210                      181.294  
236.135                      198.644  

(计算值将“10”添加到“X”和“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  

问题:

  • 我该怎么做?

【问题讨论】:

  • 小点:File.ReadAllLines() 会避免早期的代码,调用 List.ForEach 而不是直接使用 foreach 循环是没有意义的。
  • 我建议不要在您的上下文中使用 while(true)。您可以轻松地将检查移动到 while 语句的条件中:while ((line = fileReader.ReadLine()) != null) {...}.
  • @Jon Skeet:感谢您的小分:)
  • @Corey Ogburn:你为什么反对它?
  • while(true) 意味着您将永远奔跑。相反,您只是在有另一行要读取时循环。您的代码说“我将永远运行......或直到发生这种情况”,而不是说“我将运行直到发生这种情况”。不过,我会推荐@Jon Skeet 的回答而不是我的,如果你不需要的话,不需要循环。

标签: c# regex string replace richtextbox


【解决方案1】:

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

这基本上就是下面的示例所做的。它是为 .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+)");
}

【讨论】:

    【解决方案2】:

    尝试 string.Replace 就像在这个 PSEUDO 代码中一样:

    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++;
       }
    }
    

    它不是很优雅,但应该可以,对吧?

    【讨论】:

      【解决方案3】:

      既然您已经在使用 Regex 来匹配您的值,为什么不尝试使用 Regex.Replace 来更改它们。

      查看此链接了解更多信息...

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

      【讨论】:

      • 我试图弄乱Regex.Replace,但我遇到了一些麻烦......这是我正在尝试的,但它不起作用:var combinedStringBuilders = new List&lt;string&gt;(); combinedStringBuilders.Add(String.Concat(sbX + "\t" + sbY)); var someNew = Regex.Replace(line, @"(?&lt;x&gt;-?\d+\.\d+)\s+(?&lt;y&gt;-?\d+\.\d+)", combinedStringBuilders);
      猜你喜欢
      • 2018-04-08
      • 2018-04-05
      • 2015-11-28
      • 2022-11-23
      • 2017-05-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多