C # - удаление строки, которая соответствует регулярному выражению - PullRequest
3 голосов
/ 18 июля 2011

У меня есть некоторые данные .. это выглядит примерно так:

0423 222222 ADH, TEXTEXT 
0424 1234 ADH,MORE TEXT 
0425 98765 ADH, TEXT 3609 
2000 98765-4 LBL,IUC,PCA,S/N 
0010 99999-27 LBL,IUI,1.0x.25 
9000 12345678 HERE IS MORE, TEXT
9010 123-123 SOMEMORE,TEXT1231
9100 SD178 YAYFOR, TEXT01
9999 90123 HEY:HOW-TO DOTHIS

И я хотел бы удалить каждую всю строку, которая начинается с 9 xxx . Прямо сейчас я попытался заменить значение с помощью Regex. Вот что у меня есть для этого:

output = Regex.Replace(output, @"^9[\d]{3}\s+[\d*\-*\w*]+\s+[\d*\w*\-*\,*\:*\;*\.*\d*\w*]+", "");

Однако, это действительно трудно прочитать, и это фактически не удаляет всю строку.


КОД: Вот фрагмент кода, который я использую:

        try
        {
            // Resets the formattedTextRichTextBox so multiple files aren't loaded on top of eachother.
            formattedTextRichTextBox.ResetText();

            foreach (string line in File.ReadAllLines(openFile.FileName))
            {
                // Uses regular expressions to find a line that has, digit(s), space(s), digit(s) + letter(s),
                // space(s), digit(s), space(s), any character (up to 25 times).
                Match theMatch = Regex.Match(line, @"^[\.*\d]+\s+[\d\w]+\s+[\d\-\w*]+\s+.{25}");

                if (theMatch.Success)
                {
                    // Stores the matched value in string output.
                    string output = theMatch.Value;

                    // Replaces the text with the required layout.
                    output = Regex.Replace(output, @"^[\.*\d]+\s+", "");
                    //output = Regex.Replace(output, @"^9[\d]{3}\s+[\d*\-*\w*]+\s+[\d*\w*\-*\,*\:*\;*\.*\d*\w*]+", "");
                    output = Regex.Replace(output, @"\s+", " ");

                    // Sets the formattedTextRichTextBox to the string output.
                    formattedTextRichTextBox.AppendText(output);
                    formattedTextRichTextBox.AppendText("\n");
                }
            }
        }

РЕЗУЛЬТАТ: Поэтому я хотел бы, чтобы новые данные выглядели в следующем формате (удалено 9xxx) :

0423 222222 ADH, TEXTEXT 
0424 1234 ADH,MORE TEXT 
0425 98765 ADH, TEXT 3609 
2000 98765-4 LBL,IUC,PCA,S/N 
0010 99999-27 LBL,IUI,1.0x.25 

ВОПРОСЫ:

  • Есть ли более простой способ сделать это?
  • Если так, могу ли я использовать регулярные выражения для этого или я должен использовать другой способ?

Ответы [ 4 ]

2 голосов
/ 18 июля 2011

Попробуйте (использует Linq):

//Create a regex to identify lines that start with 9XXX
Regex rgx = new Regex(@"^9\d{3}");
//Below is the linq expression to filter the lines that start with 9XXX
var validLines = 
(
//This following line specifies what enumeration to pick the data from 
from ln in File.ReadAllLines(openFile.FileName)
//This following specifies what is the filter that needs to be applied to select the data. 
where !rgx.IsMatch(ln)
//This following specifies what to select from the filtered data.
select ln;
).ToArray(); //This line makes the IQueryable enumeration to an array of Strings (since variable ln in the above expression is a String)
//Finally join the filtered entries with a \n using String.Join and then append it to the textbox
formattedTextRichTextBox.AppendText = String.Join(validLines, "\n");
2 голосов
/ 18 июля 2011

Просто переформулируйте регулярное выражение, которое проверяет ваш формат на соответствие всему, что не начинается с 9 - таким образом строки, начинающиеся с 9, не добавляются в поле расширенного текста.

1 голос
/ 18 июля 2011

Почему бы вам просто не сопоставить первую часть 9ххх, использовать подстановочный знак для совпадения с остальной частью строки, это было бы намного более читабельным.

output = Regex.Replace(output, @"^9[\d{3}].*", "")

1 голос
/ 18 июля 2011

Да, есть более простой способ.Просто используйте метод Regex.Replace и предоставьте опцию Multiline.

...