应在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如何解决这个问题,或者如何正确地转义这些字符?在周围搜索一点帮助都没有。
发布于 2014-01-10 22:47:39
您应该使用verbatim strings使转义对于正则表达式更有意义。我不知道你想用\.*做什么,但是Match默认情况下只匹配它的一部分,所以我不认为这是必要的。我将使用以下模式:
@"(\[|\])"为了提高性能,请创建一个Regex对象,而不是使用静态Regex方法(因为您正在重用该模式)。而且您不需要指定IgnoreCase,因为这里您不关心字母,只关心[]符号。
Regex myRegex = new Regex(@"(\[|\])");
// later, in loop
Match match = myRegex.Match(directoryName);https://stackoverflow.com/questions/21047144
复制相似问题