1 module dmocks.name_match;
2 
3 import std.regex;
4 
5 interface NameMatch
6 {
7     bool matches(string against);
8     string toString();
9 }
10 
11 /++
12 + String name matcher
13 + Match occurs when string given are equal
14 +/
15 class NameMatchText : NameMatch
16 {
17     private string _text;
18     /// takes a string which will be tested for exact match
19     this(string text)
20     {
21         this._text = text;
22     }
23     bool matches(string against)
24     {
25         return _text == against;
26     }
27 
28     override string toString()
29     {
30         return _text;
31     }
32 }
33 
34 /++
35 + Regex pattern matcher
36 + Match occurs when there's non-empty set of matches for a given pattern
37 +/
38 class NameMatchRegex : NameMatch
39 {
40     private string _pattern;
41     private const(char)[] _flags;
42     /++
43     + creates a name matcher using std.regex module
44     + takes regex pattern and flags as described in std.regex.regex
45     +/
46     this(string pattern, const(char)[] flags="")
47     {
48         this._pattern = pattern;
49         this._flags = flags;
50     }
51 
52     bool matches(string against)
53     {
54         return !matchFirst(against, regex(_pattern, _flags)).captures.empty();
55     }
56 
57     override string toString()
58     {
59         return "(regex:)" ~ _pattern;
60     }
61 }
62 
63 unittest {
64     {
65         NameMatch a = new NameMatchText("asd");
66         assert(a.matches("asd"));
67         assert(!a.matches("qwe"));
68         assert(!a.matches("asdasd"));
69     }
70 
71     {
72         NameMatch a = new NameMatchRegex("asd");
73         assert(a.matches("asdasd"));
74         assert(a.matches("asd"));
75         assert(!a.matches("a"));
76     }
77 
78     {
79         NameMatch a = new NameMatchRegex("a..");
80         assert(a.matches("asd"));
81         assert(a.matches("asdq"));
82         assert(!a.matches("a"));
83     }
84 }