【发布时间】:2014-01-10 14:42:37
【问题描述】:
以下 Regex 应在 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 = @"[\[\]]";