Skip to content

Instantly share code, notes, and snippets.

@lindexi
Last active February 8, 2017 06:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lindexi/2bd3bccb6de194aa40ad2e09a5413000 to your computer and use it in GitHub Desktop.
Save lindexi/2bd3bccb6de194aa40ad2e09a5413000 to your computer and use it in GitHub Desktop.
通配符转正则 Wildcard to Regex
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