guneysus
9/19/2017 - 6:04 AM

PlateValidateFormatter C#

PlateValidateFormatter C#

using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace PlateHelpers
{
    public static class PlateValidate
    {
        const string REGEX_4DIGITS = @"(?!0000)[0-9]{4}"; // http://stackoverflow.com/a/9074266/1766716
        const string REGEX_3DIGITS = @"0\.[0-9]{3}"; // http://stackoverflow.com/a/28056964/1766716
        const string REGEX_2DIGITS = @"0?[1-9]|[1-9][0-9]"; // http://stackoverflow.com/a/4013014/1766716
        const string REGEX_DIGITS = @"[1-9]";

        const string REGEX_WORD = @"\w{1,3}";
        const string REGEX_VALID_PLATE = @"^(0?[1-9]|[1-9][0-9])([a-zA-Z]{1,4})((?!0000)[0-9]{4}|((?!000)[0-9]{3})|(?!00)[0-9]{2}|((?!0)[0-9]{1}))$";

        public readonly static string pattern;

        public static bool IsValid (string plate) {
            return Regex.Match(input: plate, pattern: REGEX_VALID_PLATE, options: RegexOptions.IgnoreCase).Success;
        }

        static PlateValidate () {
            // Sıra önemli. Önce 
            // { REGEX_DIGITS}|{ REGEX_3DIGITS}
            // derseniz 9999'u 9 olarak yakalıyor.
            pattern = @"^(\d{2})([a-zA-Z]{1,4})(\d{1,4})$";
        }

        public enum Country {
            TR,
            ADB
        }

        public static IList<Match> Matches(string plateNumber) {
            var matches = new List<Match>();
            foreach ( Match match in Regex.Matches(input: plateNumber, pattern: pattern, options: RegexOptions.None) ) {
                matches.Add(match);
            }
            return matches;
        }

        public static string FormatPlate(string plate, Country country) {
            string formatted = "?";

            GroupCollection groups = null;
            switch ( country ) {
                case Country.TR:
                    var matches = Matches(plate);
                    if (matches.Count > 0){
                        groups = matches [0].Groups;
                        string a = groups [1].Value, b = groups [2].Value, c = groups [3].Value;
                        formatted = $"{a} {b} {c}";
                    }

                    break;
                case Country.ADB:
                    break;
                default:
                    break;
            }

            return formatted;
        }
    }
}