Advertisement
amphibia89

O, My Girl!

May 29th, 2016
224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.28 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using System.Text.RegularExpressions;
  5.  
  6. class Program
  7. {
  8.     public static void Main()
  9.     {
  10. #if DEBUG
  11.         Console.SetIn(new StreamReader("../../input.txt"));
  12. #endif
  13.         string key = Console.ReadLine();
  14.         string text = ReadText();
  15.  
  16.         string address = ExtractAddress(text, key);
  17.         Console.WriteLine(address);
  18.     }
  19.  
  20.     private static string ExtractAddress(string text, string key)
  21.     {
  22.         string pattern = ExtractPattern(key);
  23.         var regex = new Regex(pattern);
  24.  
  25.         var addressBuilder = new StringBuilder();
  26.  
  27.         while (regex.IsMatch(text))
  28.         {
  29.             var match = regex.Match(text);
  30.             string info = match.Groups["info"].ToString();
  31.  
  32.             int position = match.Index;
  33.             if (info.Length >= 2 && info.Length <= 6)
  34.             {
  35.                 addressBuilder.Append(info);
  36.                 position += match.Length;
  37.             }
  38.             else
  39.             {
  40.                 position += match.Groups["startKey"].Length;
  41.             }
  42.            
  43.             text = text.Substring(position);
  44.         }
  45.  
  46.         return $"{addressBuilder}";
  47.     }
  48.  
  49.     private static string ExtractPattern(string key)
  50.     {
  51.         var patternBuilder = new StringBuilder();
  52.         patternBuilder.Append(Regex.Escape(key[0].ToString()));
  53.  
  54.         for (int index = 1; index < key.Length - 1; index++)
  55.         {
  56.             if (char.IsUpper(key[index]))
  57.                 patternBuilder.Append("[A-Z]*?");
  58.             else if (char.IsLower(key[index]))
  59.                 patternBuilder.Append("[a-z]*?");
  60.             else if (char.IsDigit(key[index]))
  61.                 patternBuilder.Append("\\d*?");
  62.             else
  63.                 patternBuilder.Append(Regex.Escape(key[index].ToString()));
  64.         }
  65.  
  66.         patternBuilder.Append(Regex.Escape(key[key.Length - 1].ToString()));
  67.  
  68.         return $"(?'startKey'{patternBuilder})(?'info'.*?){patternBuilder}";
  69.     }
  70.  
  71.     private static string ReadText()
  72.     {
  73.         var text = new StringBuilder();
  74.         string line = Console.ReadLine();
  75.         while (line != "END")
  76.         {
  77.             text.Append(line);
  78.             line = Console.ReadLine();
  79.         }
  80.  
  81.         return $"{text}";
  82.     }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement