- Escape the pattern to make it regex-safe. Wildcards use only
*
and?
, so the rest of the text has to be converted to literals. - Once escaped,
*
becomes\*
and?
becomes\?
, so we have to convert\*
and\?
to their respective regex equivalents,.*
and.
. - Prepend
^
and append$
to specify the beginning and end of the pattern.
/// <summary>
/// Converts a wildcard to a regex.
/// </summary>
/// <param name="pattern">The wildcard pattern to convert.</param>
/// <returns>A regex equivalent of the given wildcard.</returns>
public static string WildcardToRegex(string pattern)
{
return "^" + Regex.Escape(pattern).
Replace("\\*", ".*").
Replace("\\?", ".") + "$";
}
注:
1、匹配方法,严格遵守通配符定义,即“?” 代表一个任意字符,“*”,代表零或多个任意字符。
因此,如要实现文件通配符比较,还需要另处理兼容情况,如:*.* ,匹配的所有的文件等。