diff options
Diffstat (limited to 'RhSolutions.SkuParser.Api/Models/Product.cs')
-rw-r--r-- | RhSolutions.SkuParser.Api/Models/Product.cs | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/RhSolutions.SkuParser.Api/Models/Product.cs b/RhSolutions.SkuParser.Api/Models/Product.cs new file mode 100644 index 0000000..fd9ea45 --- /dev/null +++ b/RhSolutions.SkuParser.Api/Models/Product.cs @@ -0,0 +1,65 @@ +using System.Text.RegularExpressions; + +namespace RhSolutions.SkuParser.Models; + +public record Product +{ + /// <summary> + /// Артикул РЕХАУ в заданном формате + /// </summary> + public required string Sku + { + get => _sku; + set + { + _sku = IsValudSku(value) + ? value + : throw new ArgumentException("$Неверный артикул: {value}"); + } + } + private string _sku = string.Empty; + private const string _parsePattern = @"(?<Lead>[1\s]|^|\b)(?<Article>\d{6})(?<Delimiter>[\s13-])(?<Variant>\d{3})(\b|$)"; + private const string _validnessPattern = @"^1\d{6}[1|3]\d{3}$"; + + private static bool IsValudSku(string value) + { + return Regex.IsMatch(value.Trim(), _validnessPattern); + } + private static string GetSku(Match match) + { + string lead = match.Groups["Lead"].Value; + string article = match.Groups["Article"].Value; + string delimiter = match.Groups["Delimiter"].Value; + string variant = match.Groups["Variant"].Value; + + if (lead != "1" && delimiter == "-") + { + return $"1{article}1{variant}"; + } + else + { + return $"{lead}{article}{delimiter}{variant}"; + } + } + + /// <summary> + /// Проверка строки на наличие в ней артикула РЕХАУ + /// </summary> + /// <param name="value">Входная строка для проверки</param> + /// <param name="product">Артикул, если найден. null - если нет</param> + /// <returns>Если артикул в строке есть возвращает true, Если нет - false</returns> + public static bool TryParse(string value, out Product? product) + { + product = null; + MatchCollection matches = Regex.Matches(value, _parsePattern); + if (matches.Count == 0) + { + return false; + } + string sku = GetSku(matches.First()); + product = new Product() { Sku = sku }; + return true; + } + public override int GetHashCode() => Sku.GetHashCode(); + public override string ToString() => Sku; +}
\ No newline at end of file |