#nullable enable
using System;
using System.Text.RegularExpressions;
namespace Schaad.Accounting.Services
{
///
/// Search and replace for booking texts: plain text (taken literally) or a regular expression
/// with $1-style groups in the replacement.
///
public sealed class TextReplacement
{
// A pattern like (a+)+ on a long text could otherwise run for minutes.
private static readonly TimeSpan Timeout = TimeSpan.FromMilliseconds(500);
private static readonly Regex Spaces = new(" {2,}", RegexOptions.Compiled);
private readonly Regex regex;
private readonly string replacement;
private TextReplacement(Regex regex, string replacement)
{
this.regex = regex;
this.replacement = replacement;
}
///
/// Returns null and an error message (German, for the user) if the pattern is empty or not
/// a valid regular expression.
///
public static TextReplacement? Create(string find, string replacement, bool useRegex, bool matchCase, out string? error)
{
error = null;
if (string.IsNullOrEmpty(find))
{
error = "Bitte einen Suchtext eingeben.";
return null;
}
var options = RegexOptions.CultureInvariant | (matchCase ? RegexOptions.None : RegexOptions.IgnoreCase);
try
{
return useRegex
? new TextReplacement(new Regex(find, options, Timeout), replacement)
// Plain text: both the pattern and a '$' in the replacement are literal.
: new TextReplacement(new Regex(Regex.Escape(find), options, Timeout), replacement.Replace("$", "$$"));
}
catch (ArgumentException ex)
{
error = $"Ungültiger regulärer Ausdruck: {ex.Message}";
return null;
}
}
public bool IsMatch(string text) => regex.IsMatch(text);
/// The pattern took too long on this text.
public string Apply(string text) => regex.Replace(text, replacement);
///
/// Removes leading/trailing spaces and collapses repeated spaces.
///
public static string Tidy(string text) => Spaces.Replace(text.Trim(), " ");
}
}