Last active
October 20, 2017 16:03
-
-
Save deanebarker/99fe3e110d23796a60f4660739dac644 to your computer and use it in GitHub Desktop.
A class to match strings based on a specified method and options.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// If you think it's brilliant, then this is completely intentional. | |
// If you think it's dumb, then this is intended ironically because I'm just _that_ smart. | |
StringMatcher.IsMatch("Deane Barker", "deane ", StringMatchMethod.Starts, StringMatchOptions.IgnoreCase | StringMatchOptions.Trim); // True | |
StringMatcher.IsMatch("Deane Barker", "Barker", StringMatchMethod.Ends); // True | |
StringMatcher.IsMatch("Deane Barker", "ARK", StringMatchMethod.Contains, StringMatchOptions.IgnoreCase); // True | |
// etc. | |
// In reality, this is intended for use with a particular CMS, so that the editing interface can be dynamically generated | |
// based on the code. A dropdown will generate for the values in StringMatchMethod, and checkboxes will generate for the | |
// flags in StringMatchOptions. Then this code will execute based on that input, directly translated into the enums. | |
// (So, you see, it has an actual purpose and you should feel badly for making fun of it.) | |
public static class StringMatcher | |
{ | |
public static bool IsMatch(string input, string pattern, StringMatchMethod method = StringMatchMethod.Exact, StringMatchOptions options = StringMatchOptions.None) | |
{ | |
if (options.HasFlag(StringMatchOptions.IgnoreCase)) | |
{ | |
input = input.ToLower(); | |
pattern = pattern.ToLower(); | |
} | |
if (options.HasFlag(StringMatchOptions.Trim)) | |
{ | |
input = input.Trim(); | |
pattern = pattern.Trim(); | |
} | |
switch (method) | |
{ | |
case StringMatchMethod.Starts: | |
return input.StartsWith(pattern); | |
case StringMatchMethod.Ends: | |
return input.EndsWith(pattern); | |
case StringMatchMethod.Contains: | |
return input.Contains(pattern); | |
case StringMatchMethod.Regex: | |
return Regex.IsMatch(input, pattern); | |
// Default is "Exact" | |
default: | |
return input == pattern; | |
} | |
} | |
} | |
public enum StringMatchMethod | |
{ | |
Exact, | |
Starts, | |
Ends, | |
Contains, | |
Regex | |
} | |
[Flags] | |
public enum StringMatchOptions : short | |
{ | |
None = 0, | |
IgnoreCase = 1, | |
Trim = 2 | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@daveaglick If I was a developer, I would have known this.