using System; using System.IO; using System.Text.RegularExpressions; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConvertRomanToNumeral { public class RomanNumber { public string Numeral { get; set; } public int Value { get; set; } public int Hierarchy { get; set; } } class Program { public static List RomanNumbers = new List { new RomanNumber {Numeral = "M", Value = 1000, Hierarchy = 4}, new RomanNumber {Numeral = "D", Value = 500, Hierarchy = 4}, new RomanNumber {Numeral = "C", Value = 100, Hierarchy = 3}, new RomanNumber {Numeral = "L", Value = 50, Hierarchy = 3}, new RomanNumber {Numeral = "X", Value = 10, Hierarchy = 2}, new RomanNumber {Numeral = "V", Value = 5, Hierarchy = 2}, new RomanNumber {Numeral = "I", Value = 1, Hierarchy = 1} }; static void Main(string[] args) { if (args.Length == 0) return; string path = args[0]; if (Directory.Exists(path)) { ProcessDirectory(path); } } public static void ProcessDirectory(string targetDirectory) { string[] fileEntries = Directory.GetFiles(targetDirectory); foreach (string fileName in fileEntries) ProcessFile(fileName); string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory); foreach (string subdirectory in subdirectoryEntries) ProcessDirectory(subdirectory); } public static void ProcessFile(string path) { string text = System.IO.File.ReadAllText(path); string pattern = @"()(Chapter )([IVCLXDM]+?)()"; string output = Regex.Replace(text, pattern, delegate(Match match) { return match.Groups[1].Value + match.Groups[2].Value + ConvertRomanNumeralToInt(match.Groups[3].Value) + match.Groups[4].Value; }); if(Regex.IsMatch(text, pattern)) System.IO.File.WriteAllText(path, output); Console.WriteLine("Processed file '{0}'.", path); } public static string ConvertRomanNumeralToInt(string romanNumeralString) { if (romanNumeralString == null) return int.MinValue.ToString(); var total = 0; for (var i = 0; i < romanNumeralString.Length; i++) { var current = romanNumeralString[i].ToString(); var curRomanNum = RomanNumbers.First(rn => rn.Numeral.ToUpper() == current.ToUpper()); if (i + 1 == romanNumeralString.Length) { total += curRomanNum.Value; break; } var next = romanNumeralString[i + 1].ToString(); var nextRomanNum = RomanNumbers.First(rn => rn.Numeral.ToUpper() == next.ToUpper()); if (curRomanNum.Hierarchy == (nextRomanNum.Hierarchy - 1)) { total += nextRomanNum.Value - curRomanNum.Value; i++; } else { total += curRomanNum.Value; } } return total.ToString(); } } }