Advertisement
Guest User

filter with generator

a guest
Apr 28th, 2017
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.45 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text.RegularExpressions;
  5.  
  6. namespace Filter
  7. {
  8.     class Program
  9.     {
  10.         static void Main(string[] args)
  11.         {
  12.             if (args.Length < 3)
  13.             {
  14.                 Console.WriteLine("Usage: filter input output regex");
  15.                 return;
  16.             }
  17.             string input = args[0];
  18.             string output = args[1];
  19.             string regex = args[2];
  20.  
  21.             if (!File.Exists(input))
  22.             {
  23.                 Console.WriteLine("Could not find input file.");
  24.                 return;
  25.             }
  26.  
  27.             using (FileStream read = File.OpenRead(input))
  28.             {
  29.                 using (TextReader reader = new StreamReader(read))
  30.                 {
  31.                     File.WriteAllLines(output, GetLines(reader, regex));
  32.                 }
  33.             }
  34.         }
  35.  
  36.         private static IEnumerable<string> GetLines(TextReader reader, string regex)
  37.         {
  38.             Regex x = new Regex(regex);
  39.             while (true)
  40.             {
  41.                 string line = reader.ReadLine();
  42.                 if (line != null)
  43.                 {
  44.                     if (x.IsMatch(line))
  45.                     {
  46.                         yield return line;
  47.                     }
  48.                 }
  49.                 else
  50.                 {
  51.                     break;
  52.                 }
  53.             }
  54.         }
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement