>using System; >using System.Collections.Generic; >using System.Linq; >using System.Text; >using System.Threading.Tasks; > >namespace RegExpTest >{ > class Program > { > static void Main(string[] args) > { > Console.WriteLine(ICRFormat("16Mh1234")); > Console.WriteLine(ICRFormat("15D35999")); > Console.WriteLine(ICRFormat("115D35999")); > Console.Read(); > } > > static String ICRFormat(String UnformattedICR) > { > System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("^(\\d\\d)([A-Z]{1,2})(\\d{1,6})$", System.Text.RegularExpressions.RegexOptions.IgnoreCase); > System.Text.RegularExpressions.MatchCollection matches = regex.Matches(UnformattedICR); > if (matches.Count == 1) > { > System.Text.RegularExpressions.Match match = matches[0]; > return match.Groups[1] + " " + match.Groups[2].ToString().ToUpper() + " " + match.Groups[3]; > } > return "Invalid Entry"; > } > } >} > >Neat! Maybe better to make the Regex static rather than instantiating on each call. Toyed with incorporating it into a class :
public class IEReg { static System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("^(\\d\\d)([A-Z]{1,2})(\\d{1,6})$", System.Text.RegularExpressions.RegexOptions.IgnoreCase); private string ieReg, ieCounty, ieNumber; private int? ieYear; public IEReg(string s) { System.Text.RegularExpressions.MatchCollection matches = regex.Matches(s); if (matches.Count == 1) { System.Text.RegularExpressions.Match match = matches[0]; ieReg = match.Groups[1] + " " + match.Groups[2].ToString().ToUpper() + " " + match.Groups[3]; ieYear = int.Parse(match.Groups[1].Value); ieCounty = match.Groups[2].Value; ieNumber = match.Groups[3].Value; } else { ieReg = "Invalid Entry"; } } public string ICRString { get { return ieReg; } } public int? Year { get { return ieYear; } } public string County { get { return ieCounty; } } public string Number { get { return ieNumber; } } public static IEnumerable<IEReg> Items(List<string> list) { return list.Select(x => new IEReg(x)); } }which would allow:
List<string> numbers = new List<string> { "16Mh1234", "15D35999", "115D35999", "15D35123" }; var xx = IEReg.Items(numbers).Where(x => x.Year == 15); //or IEReg.Items(numbers).OrderBy(x => x.Year).ThenBy(x => x.County).ToList().ForEach(x=>Console.WriteLine(x.ICRString)); //etc