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 24 bool matches(string against) 25 { 26 return _text == against; 27 } 28 29 override string toString() 30 { 31 return _text; 32 } 33 } 34 35 /++ 36 + Regex pattern matcher 37 + Match occurs when there's non-empty set of matches for a given pattern 38 +/ 39 class NameMatchRegex : NameMatch 40 { 41 private string _pattern; 42 private const(char)[] _flags; 43 /++ 44 + creates a name matcher using std.regex module 45 + takes regex pattern and flags as described in std.regex.regex 46 +/ 47 this(string pattern, const(char)[] flags = "") 48 { 49 this._pattern = pattern; 50 this._flags = flags; 51 } 52 53 bool matches(string against) 54 { 55 return !matchFirst(against, regex(_pattern, _flags)).captures.empty(); 56 } 57 58 override string toString() 59 { 60 return "(regex:)" ~ _pattern; 61 } 62 } 63 64 unittest 65 { 66 { 67 NameMatch a = new NameMatchText("asd"); 68 assert(a.matches("asd")); 69 assert(!a.matches("qwe")); 70 assert(!a.matches("asdasd")); 71 } 72 { 73 NameMatch a = new NameMatchRegex("asd"); 74 assert(a.matches("asdasd")); 75 assert(a.matches("asd")); 76 assert(!a.matches("a")); 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 }