65 lines
1.9 KiB
C#
65 lines
1.9 KiB
C#
|
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;
|
|||
|
}
|