Regex Заменить 2 значения в C # - PullRequest
1 голос
/ 28 июля 2011

Если у меня есть RichTextBox_1, который выглядит следующим образом:

TEXT  TEXT  444.444 555.555 270
TEXT  TEXT  444.444 555.555 270
TEXT  TEXT  444.444 555.555 270

И я хотел бы заменить значения в третьем столбце значениями в RichTextBox_2:

123.456
12.345
-123.987

И значения в четвертом столбце со значениями в RichTextBox_3:

-9.876
98.76
-987.654

Чтобы получить окончательный файл:

TEXT  TEXT  123.456 9.876 270
TEXT  TEXT  12.345 98.76 270
TEXT  TEXT  -123.987 -987.654 270

Как я могу сделать это, используя REGEX ?


РЕДАКТИРОВАТЬ:

КОД:

(Разбивает значенияиз ListBox в: RichTextBox_2 и RichTextBox_3. Вместо ListBox я переместил все это в RichTextBox_1)

private void calculateXAndYPlacement()
{
 // 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");
     }
  });
 } 

Я пытался бездельничатьс Regex.Replace, но у меня возникли некоторые проблемы ... Вот то, что я, что пытается, и это не работает:

var combinedStringBuilders = new List<string>();
combinedStringBuilders.Add(String.Concat(sbX + "\t" + sbY));
var someNew = Regex.Replace(line, @"(?<x>-?\d+\.\d+)\s+(?<y>-?\d+\.\d+)", combinedStringBuilders);

Ответы [ 3 ]

0 голосов
/ 11 августа 2011
            // 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 = "";
            while ((fileLines = fileReader.ReadLine()) != null)
                fileList.Add(fileLines);

            // 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);

                    // Store the old X and Y values.
                    oldXRichTextBox.AppendText(xValue + Environment.NewLine);
                    oldYRichTextBox.AppendText(yValue + Environment.NewLine);
                    try
                    {
                        // 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((doubleXValue - doubleX).ToString());

                        double doubleY = double.Parse(yValue);
                        double doubleYValue = double.Parse(yDisplacementTextBox.Text);
                        StringBuilder sbY = new StringBuilder();

                        sbY.AppendLine((doubleY + doubleYValue).ToString());

                        calculateXRichTextBox.AppendText(sbX + "");
                        calculateYRichTextBox.AppendText(sbY + "");

                        // Removes the blank lines.
                        calculateXRichTextBox.Text = Regex.Replace(calculateXRichTextBox.Text, @"^\s*$(\n|\r|\r\n)", "", RegexOptions.Multiline);
                        calculateYRichTextBox.Text = Regex.Replace(calculateYRichTextBox.Text, @"^\s*$(\n|\r|\r\n)", "", RegexOptions.Multiline);
                    }
0 голосов
/ 11 августа 2011

Вы должны просто разбить вашу строку на строки, а затем на столбцы, я предполагаю, что у вашего текста есть конец строки msdos (cr + lf).

public string ReplaceColumn( string text, int col, List<string> newValues ){
  var sb = new StringBuilder();
  var lines = Regex.Split( text, "[\r\n]+" ); // split into lines
  for ( int row = 0; row < lines.Count ; row++ ){
    var line = lines[row];
    var columns = Regex.Split( line, "[\s]+" ); // split into columns

    // replace the chosen column for this row
    columns[col] = newvalues[row];

    // rebuild the line and store it
    sb.Append( String.Join( " ", columns );
    sb.Append( "\r\n" ); // or whatever line ending you want

  }
  return sb.ToString();
}

Конечно, вышеупомянутое не работает слишком хорошо, если ваши текстовые столбцы содержат пробелы.

0 голосов
/ 28 июля 2011

Общий неязыковой метод.
(Я не сделал достаточно C #, чтобы написать конкретные)

5 (только) столбцы должны проверяться первыми.
Это можно сделать, чередуя непробельные символы
затем пробел.

регулярное выражение: ^(\s*\S+\s+\S+\s+)(\S+)(\s+)(\S+)(\s+\S+\s*)$
replacemnt: ${1}${sbX}${3}${sbY}${5}

Откройте 3 файла. В цикле while читайте строки из каждого файла.
Проверьте оба sbX / sbY на отсутствие пробелов.
Сделайте замену, добавьте измененную строку в файл.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...