【问题标题】:Regex in C# finding all foldernames containing [ | ]C# 中的正则表达式查找包含 [ | 的所有文件夹名称]
【发布时间】: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 = @"[\[\]]";

标签: c# regex


【解决方案1】:

转义模式字符串:

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

或者:

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

如需更深入地了解字符串和字符串转义序列,请访问MSDN

【讨论】:

  • 请注意,括号\.*s 在这种情况下是没有用的,(\[|\]) 也可以写成更简单的[[\]]
【解决方案2】:

您应该使用verbatim strings 使转义对正则表达式更有意义。我不确定你想用\.* 做什么,但Match 默认只匹配其中的一部分,所以我认为没有必要。我会使用以下模式:

@"(\[|\])"

为了提高性能,请创建一个Regex 对象,而不是使用静态Regex 方法(因为您正在重用该模式)。而且你不需要指定IgnoreCase,因为你不关心这里的字母,只关心[]符号。

Regex myRegex = new Regex(@"(\[|\])");
// later, in loop
Match match = myRegex.Match(directoryName);

【讨论】:

    【解决方案3】:

    基于 Tim S. 的回答,您可以将 GetSubFoldersMatching 创建为重载函数,以便您可以将现有的 Regex 对象或字符串传递给它,它会处理它。通过重用 Regex 对象,您还应该获得轻微的性能提升。

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

    【讨论】:

      【解决方案4】:

      只需在你的模式前添加@:

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

      它会起作用的。

      这是整个事情的一个例子。

              List<string>  n = new List<string>();
              n.AddRange( new string[] { "an folder ] ",
                  "and ] another",
                  "not this one",
                  "[so] this is",
                  "and [ a few more]",
                  "OR num2 either",
                  "lorem ipsum["});
      
              string pattern =@"(\[|\])"; // you don't need your \.* parts
              List<string> directoriesMatchingPattern = new List<string>();
              foreach (string d in n)
              {
                  if (Regex.Match(d, pattern).Success)
                  {
                      directoriesMatchingPattern.Add(d);
                  }
              }
      

      【讨论】:

        猜你喜欢
        • 2012-10-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多