Parser.cs 919 B

12345678910111213141516171819202122232425262728293031
  1. using System.Drawing;
  2. using System.Text.RegularExpressions;
  3. namespace Day18;
  4. public partial class Parser
  5. {
  6. [GeneratedRegex(@"([UDLR])\s+(\d+)\s+\((.*)\)")]
  7. private partial Regex LineMatch();
  8. public IEnumerable<Instruction> Parse(string inputFile)
  9. {
  10. using var reader = File.OpenText(inputFile);
  11. var colorConverter = new ColorConverter();
  12. while (!reader.EndOfStream)
  13. {
  14. var line = reader.ReadLine()!;
  15. var match = LineMatch().Match(line);
  16. if (!match.Success)
  17. {
  18. throw new Exception($"Invalid instruction: {line}");
  19. }
  20. yield return new Instruction(
  21. match.Groups[1].Value[0],
  22. int.Parse(match.Groups[2].Value),
  23. (Color)colorConverter.ConvertFromString(match.Groups[3].Value)!);
  24. }
  25. }
  26. }