/// <summary> /// Создает новый объект MessageTemplate, основанный на заданном шаблоне /// </summary> /// <param name="templateText">Текст шаблона</param> /// <exception cref="ArgumentNullException"/> /// <exception cref="MessageTemplateSyntaxException"/> public MessageTemplate(string templateText) { if (templateText == null) { throw new ArgumentNullException(nameof(templateText)); } int position = 0; foreach (Match match in FieldRegex.Matches(templateText)) { // часть шаблона перед или между подстановками if (position < match.Index) { var text = templateText.Substring(position, match.Index - position); AddLiteralText(text); } position = match.Index + match.Length; // подстановка ProcessMatch(match); } // часть шаблона после последней подстановки if (position < templateText.Length) { var text = templateText.Substring(position); AddLiteralText(text); } }
public static Field Parse(string text, string fieldName) { if (string.IsNullOrWhiteSpace(text)) { throw new ExpectedException($"{fieldName}: You must specify a positive integer or a named column for a field"); } if (int.TryParse(text, out var index)) { if (index > 0) { return(new Field(fieldName, index)); } throw new Exception($"{fieldName}: {text} is an invalid index. Use a positive integer or a named column."); } var match = FieldRegex.Match(text); if (match.Success) { var patternText = match.Groups["pattern"].Value; var countText = match.Groups["count"].Value; Regex regex; try { regex = new Regex(patternText); } catch (ArgumentException exception) { throw new ExpectedException($"{fieldName}: {text} is not a valid regular expression: {exception.Message}"); } if (!int.TryParse(countText, out var count)) { count = 1; } return(new Field(fieldName, regex, count)); } return(new Field(fieldName, text)); }