using System;
using System.Linq;
using System.Text.RegularExpressions;
using JetBrains.Annotations;
using WireMock.Validation;
namespace WireMock.Matchers
{
///
/// Regular Expression Matcher
///
///
///
public class RegexMatcher : IStringMatcher, IIgnoreCaseMatcher
{
private readonly string[] _patterns;
private readonly Regex[] _expressions;
///
public MatchBehaviour MatchBehaviour { get; }
///
/// Initializes a new instance of the class.
///
/// The pattern.
/// Ignore the case from the pattern.
public RegexMatcher([NotNull, RegexPattern] string pattern, bool ignoreCase = false) : this(new[] { pattern }, ignoreCase)
{
}
///
/// Initializes a new instance of the class.
///
/// The match behaviour.
/// The pattern.
/// Ignore the case from the pattern.
public RegexMatcher(MatchBehaviour matchBehaviour, [NotNull, RegexPattern] string pattern, bool ignoreCase = false) : this(matchBehaviour, new[] { pattern }, ignoreCase)
{
}
///
/// Initializes a new instance of the class.
///
/// The patterns.
/// Ignore the case from the pattern.
public RegexMatcher([NotNull, RegexPattern] string[] patterns, bool ignoreCase = false) : this(MatchBehaviour.AcceptOnMatch, patterns, ignoreCase)
{
}
///
/// Initializes a new instance of the class.
///
/// The match behaviour.
/// The patterns.
/// Ignore the case from the pattern.
public RegexMatcher(MatchBehaviour matchBehaviour, [NotNull, RegexPattern] string[] patterns, bool ignoreCase = false)
{
Check.NotNull(patterns, nameof(patterns));
_patterns = patterns;
IgnoreCase = ignoreCase;
MatchBehaviour = matchBehaviour;
RegexOptions options = RegexOptions.Compiled;
if (ignoreCase)
{
options |= RegexOptions.IgnoreCase;
}
_expressions = patterns.Select(p => new Regex(p, options)).ToArray();
}
///
public double IsMatch(string input)
{
double match = MatchScores.Mismatch;
if (input != null)
{
try
{
match = MatchScores.ToScore(_expressions.Select(e => e.IsMatch(input)));
}
catch (Exception)
{
// just ignore exception
}
}
return MatchBehaviourHelper.Convert(MatchBehaviour, match);
}
///
public virtual string[] GetPatterns()
{
return _patterns;
}
///
public virtual string Name => "RegexMatcher";
///
public bool IgnoreCase { get; }
}
}