要导入Microsoft.VisualBasic.CompilerServices库,我的win7下的vs2008,每次点导入都有可能失去响应,试试先了解,意思是把原来字符串的abc*.txt换成abc\*.txt就变成了正则表达式了。找到了 private static Regex WildcardToRegex(string wildcard) { var pattern = Regex.Escape(wildcard); if (Path.DirectorySeparatorChar == '/') { // regex wildcard adjustments for *nix-style file systems pattern = pattern .Replace(@"\*\*/", ".*") //For recursive wildcards /**/, include the current directory. .Replace(@"\*\*", ".*") // For recursive wildcards that don't end in a slash e.g. **.txt would be treated as a .txt file at any depth .Replace(@"\*", @"[^/]*(/)?") // For non recursive searches, limit it any character that is not a directory separator .Replace(@"\?", "."); // ? translates to a single any character } else { // regex wildcard adjustments for Windows-style file systems pattern = pattern .Replace("/", @"\\") // On Windows, / is treated the same as \. .Replace(@"\*\*\\", ".*") //For recursive wildcards \**\, include the current directory. .Replace(@"\*\*", ".*") // For recursive wildcards that don't end in a slash e.g. **.txt would be treated as a .txt file at any depth .Replace(@"\*", @"[^\\]*(\\)?") // For non recursive searches, limit it any character that is not a directory separator .Replace(@"\?", "."); // ? translates to a single any character } return new Regex('^' + pattern + '$', RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture); } 一个个的试试,多谢几位
.Net 框架自带算法,不需要使用第三方库
private static Regex WildcardToRegex(string wildcard)
{
var pattern = Regex.Escape(wildcard);
if (Path.DirectorySeparatorChar == '/')
{
// regex wildcard adjustments for *nix-style file systems
pattern = pattern
.Replace(@"\*\*/", ".*") //For recursive wildcards /**/, include the current directory.
.Replace(@"\*\*", ".*") // For recursive wildcards that don't end in a slash e.g. **.txt would be treated as a .txt file at any depth
.Replace(@"\*", @"[^/]*(/)?") // For non recursive searches, limit it any character that is not a directory separator
.Replace(@"\?", "."); // ? translates to a single any character
}
else
{
// regex wildcard adjustments for Windows-style file systems
pattern = pattern
.Replace("/", @"\\") // On Windows, / is treated the same as \.
.Replace(@"\*\*\\", ".*") //For recursive wildcards \**\, include the current directory.
.Replace(@"\*\*", ".*") // For recursive wildcards that don't end in a slash e.g. **.txt would be treated as a .txt file at any depth
.Replace(@"\*", @"[^\\]*(\\)?") // For non recursive searches, limit it any character that is not a directory separator
.Replace(@"\?", "."); // ? translates to a single any character
} return new Regex('^' + pattern + '$', RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
}
一个个的试试,多谢几位