Last active
February 8, 2017 06:25
-
-
Save lindexi/2bd3bccb6de194aa40ad2e09a5413000 to your computer and use it in GitHub Desktop.
通配符转正则 Wildcard to Regex
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
public static class WildcardRegexString | |
{ | |
/// <summary> | |
/// 通配符转正则 | |
/// </summary> | |
/// <param name="wildcardStr"></param> | |
/// <returns></returns> | |
public static string GetWildcardRegexString(string wildcardStr) | |
{ | |
Regex replace = //new Regex("[.$^{\\[(|)*+?\\\\]"); | |
_regex; | |
return replace.Replace(wildcardStr, | |
delegate (Match m) | |
{ | |
switch (m.Value) | |
{ | |
case "?": | |
return ".?"; | |
case "*": | |
return ".*"; | |
default: | |
return "\\" + m.Value; | |
} | |
}) + "$"; | |
} | |
/// <summary> | |
/// 获取通配符的正则 | |
/// </summary> | |
/// <param name="wildcarStr"></param> | |
/// <param name="ignoreCase">是否忽略大小写</param> | |
/// <returns></returns> | |
public static Regex GetWildcardRegex(string wildcarStr, bool ignoreCase) | |
{ | |
if (ignoreCase) | |
{ | |
return new Regex(GetWildcardRegexString(wildcarStr)); | |
} | |
return new Regex(GetWildcardRegexString(wildcarStr), RegexOptions.IgnoreCase); | |
} | |
private static Regex _regex = new Regex("[.$^{\\[(|)*+?\\\\]", RegexOptions.Compiled); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://lindexi.oschina.io/lindexi/post/C-%E9%80%9A%E9%85%8D%E7%AC%A6%E8%BD%AC%E6%AD%A3%E5%88%99/