【问题标题】:Regular expression where * matches all characters except back slash and new line正则表达式,其中 * 匹配除反斜杠和换行符之外的所有字符
【发布时间】:2013-02-18 13:19:24
【问题描述】:

这就是我要实现的目标

gitignore 文档链接:gitignore manpage

否则,git 将模式视为适合 fnmatch(3) 使用的 shell glob,带有 FNM_PATHNAME 标志:模式中的通配符将不匹配路径名中的 /。例如,“Documentation/.html” 匹配“Documentation/git.html”,但不匹配“Documentation/ppc/ppc.html”或“tools/perf/Documentation/perf.html”。 p>

我确实在代码中尝试过这个

patternEscapedForStar = patternEscaped.Replace(@"\*", "[^\\]*");

上面一行是改变正则表达式中 * 的行为,以匹配文件或文件夹路径中除“\”之外的所有字符。但是,它似乎与预期的不匹配。由于我使用的是 gitignore 模式,所以在上面提到的替换之前,我确实将 blob 转换为正则表达式。

顺便说一句,我涉足正则表达式,但在任何方面都不是专家。感谢您的帮助。

编辑:

这是完整的代码

public static bool PatternMatch(string str, string pattern, string type)
{
string patternEscaped = string.Empty;
string patternEscapedForStar = string.Empty;                                              
string patternEscapedForQuestionMark = string.Empty;
bool returnValue = false;

try
{
    patternEscaped = Regex.Escape(pattern);

    patternEscapedForStar = patternEscaped.Replace(@"\*", ".*");
    if (type == "P")
    {
        patternEscapedForStar = patternEscapedForStar.Replace(@".*", "[^\\]*");
    }

    patternEscapedForQuestionMark = patternEscapedForStar.Replace(@"\?", ".");

    returnValue = new Regex(patternEscapedForQuestionMark, RegexOptions.IgnoreCase | RegexOptions.Singleline).IsMatch(str);

 }
 catch (Exception ex)
 {
     Log.LogException(ex);
 }
    return returnValue;
}

【问题讨论】:

  • 肯定确定您的输入字符串patternEscaped 包含"\\*" 而不仅仅是"*" 吗?
  • @Nolonar 输入字符串仅包含“”,我将其替换为 > [^\](零个或多个字符,“\”除外。因为它是 windows第二个“\”用于在字符串中转义。
  • “与预期不符”。你能举一个verbatim 的例子吗?
  • 事情是;您的代码似乎使用string.Replace()@"\*"(又名"\\*")替换为"[^\\]*"。对于字符串,* 是有效字符,不需要转义。请改用patternEscaped.Replace("*", "[^\\]*")
  • @Nolonar pattern: folder*\folder111 string: folder11\folder111\somefile.txt 这仍然给我错误且不匹配,我确实将“\*”更改为“*”

标签: c# regex git gitignore


【解决方案1】:

您面临的问题是因为"[^\\]*"。由于 \ 用于描述转义字符,"\\" 解析为文字 \ 字符,这是您的 Regex 将看到的唯一字符。

这就是一切都爆炸的地方;由于\ 也是Regex 的特殊字符,所以我们得到了问题,Regex 并不真正知道如何处理@"[^\]*"

长话短说:正确答案是

patternEscapedForStar = patternEscaped.Replace(@"\*", @"[^\\]*");

patternEscapedForStar = patternEscaped.Replace(@"\*", "[^\\\\]*");

【讨论】:

  • patternEscapedForStar = patternEscaped.Replace(@"\*", "[^\\\\]*");这行得通。你太棒了!非常感谢你的帮助。我确实接受了您的回答,但是由于我还没有足够的分数,因此我无法投票赞成该答案。再次感谢。
  • 我试过了,但是它给了我之前发布的相同错误。同样在第一条评论中,我的意思是 [^\\] 但是在我发布时删除了一个斜杠。我想这是一件好事,因为对此的替代答案有效。再次感谢。
  • 我明白了。不知道为什么答案的第一部分不起作用,但我很高兴它有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-09
  • 1970-01-01
  • 2014-03-22
  • 2019-08-26
  • 2023-03-13
相关资源
最近更新 更多