Skip to main content
 首页 » 编程设计

c#之C# 中的正则表达式查找包含 [ | 的所有文件夹名称]

2024年01月24日25xiaohuochai

应在 C# 中处理以下正则表达式:

我想找到所有包含“[”或“]”的字符串。

它应该匹配以下字符串;

...an folder ] ... 
...and ] another... 
...[so] this is... 
...and [ a few more]... 
...lorem ipsum[... 

以下代码无法编译:

string pattern ="\.*(\[|\])\.*"; 
List<string> directoriesMatchingPattern=  Util.GetSubFoldersMatching(attachmentDirectory,pattern); 

和实现:

     public static List<string> GetSubFoldersMatching(string attachmentDirectory, string pattern) 
        { 
            List<string> matching = new List<string>(); 
            foreach (string directoryName in Directory.GetDirectories(attachmentDirectory)) 
            { 
                Match match = Regex.Match(directoryName, pattern, RegexOptions.IgnoreCase); 
                if (match.Success) 
                { 
                    matching.Add(directoryName); 
                } 
                else 
                { 
                    matching.AddRange(GetSubFoldersMatching(directoryName,pattern)); 
                } 
            } 
            return matching; 
        } 

Visual Studio 显示的错误是:

Error   Unrecognized escape sequence 

如何解决这个问题,或者如何正确地转义这个字符?谷歌搜索根本没有帮助。

请您参考如下方法:

转义模式字符串:

string pattern ="\\.*(\\[|\\])\\.*"; 

或者:

string pattern = @"\.*(\[|\])\.*"; 

要更深入地了解字符串和字符串转义序列,请在此处查看 MSDN .