以下正则表达式应该在C#中处理:
我想找到包含'['或']'的所有字符串.
它应该匹配以下字符串;
...an folder ] ...
...and ] another...
...[so] this is...
...and [ a few more]...
...lorem ipsum[...
Run Code Online (Sandbox Code Playgroud)
以下代码不会编译:
string pattern ="\.*(\[|\])\.*";
List<string> directoriesMatchingPattern= Util.GetSubFoldersMatching(attachmentDirectory,pattern);
Run Code Online (Sandbox Code Playgroud)
并实施:
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;
}
Run Code Online (Sandbox Code Playgroud)
Visual Studio显示的错误是:
Error Unrecognized escape sequence
Run Code Online (Sandbox Code Playgroud)
如何解决这个问题,或者如何正确地逃避这些问题呢?谷歌搜索没有任何帮助.
转义模式字符串:
string pattern ="\\.*(\\[|\\])\\.*";
Run Code Online (Sandbox Code Playgroud)
要么:
string pattern = @"\.*(\[|\])\.*";
Run Code Online (Sandbox Code Playgroud)
有关字符串和字符串转义序列的更深入研究,请参见MSDN.