C# 正则表达式将不匹配
Posted
技术标签:
【中文标题】C# 正则表达式将不匹配【英文标题】:C# Regex will not match 【发布时间】:2021-07-29 04:45:33 【问题描述】:尝试编写将提取一个月的所有日志文件并将其压缩的代码。我看不到让 RegEx 模式在我的代码中工作。下面是我用来测试的沙盒控制台应用程序:
public static void Main(string[] args)
var targetDate = DateTime.Now.AddMonths(-1);
var pattern = $@"c:\\logs\\client-targetDate.Year-targetDate.Month:d2-.*.log";
Regex regex = new Regex(Regex.Escape(pattern), RegexOptions.IgnoreCase);
var files = Directory.EnumerateFiles(@"c:\logs").Where(f => regex.IsMatch(f)).ToList();
foreach(var file in files)
Console.WriteLine(file);
枚举文件如下所示:
c:\logs\client-2021-03-01.log
c:\logs\client-2021-03-02.log
c:\logs\client-2021-03-03.log
c:\logs\client-2021-03-04.log
c:\logs\client-2021-03-05.log
c:\logs\client-2021-03-06.log
c:\logs\client-2021-03-07.log
c:\logs\client-2021-03-08.log
c:\logs\client-2021-03-09.log
c:\logs\client-2021-03-10.log
c:\logs\client-2021-03-11.log
c:\logs\client-2021-03-12.log
c:\logs\client-2021-03-13.log
c:\logs\client-2021-03-14.log
c:\logs\client-2021-03-15.log
c:\logs\client-2021-03-16.log
c:\logs\client-2021-03-17.log
c:\logs\client-2021-03-18.log
c:\logs\client-2021-03-19.log
c:\logs\client-2021-03-20.log
c:\logs\client-2021-03-21.log
c:\logs\client-2021-03-22.log
c:\logs\client-2021-03-23.log
c:\logs\client-2021-03-24.log
c:\logs\client-2021-03-25.log
c:\logs\client-2021-03-26.log
c:\logs\client-2021-03-27.log
c:\logs\client-2021-03-28.log
c:\logs\client-2021-03-29.log
c:\logs\client-2021-03-30.log
c:\logs\client-2021-03-31.log
c:\logs\client-2021-04-01.log
c:\logs\client-2021-04-02.log
c:\logs\client-2021-04-03.log
c:\logs\client-2021-04-05.log
c:\logs\client-2021-04-06.log
c:\logs\client-2021-04-07.log
c:\logs\client-2021-04-08.log
c:\logs\client-2021-04-09.log
c:\logs\client-2021-04-10.log
c:\logs\client-2021-04-12.log
c:\logs\client-2021-04-13.log
c:\logs\client-2021-04-14.log
c:\logs\client-2021-04-15.log
c:\logs\client-2021-04-16.log
c:\logs\client-2021-04-17.log
c:\logs\client-2021-04-18.log
c:\logs\client-2021-04-19.log
c:\logs\client-2021-04-20.log
c:\logs\client-2021-04-21.log
c:\logs\client-2021-04-22.log
c:\logs\client-2021-04-23.log
c:\logs\client-2021-04-24.log
c:\logs\client-2021-04-25.log
c:\logs\client-2021-04-26.log
c:\logs\client-2021-04-27.log
我已经针对几个测试人员检查了 RegEx 模式,包括一个用于 .NET 的测试人员,并且它通过了,所以我不确定差异在哪里。任何帮助将不胜感激。
【问题讨论】:
你为什么要逃避你的正则表达式? 恕我直言,您不需要正则表达式来完成此操作。 @Codexer 我很好奇你建议的解决方案。 您只需要删除Regex.Escape()
。您两次转义了反斜杠。
【参考方案1】:
你逃避你的模式的方式是打破正则表达式。以下是您如何做到这一点的示例:
var source = @"c:\logs\client-2021-03-01.log";
var pattern = $@"c:\\logs\\client-2021-03-.*.log";
var regex = new Regex(pattern, RegexOptions.IgnoreCase);
var match = regex.Match(source); // This is now true
【讨论】:
以上是关于C# 正则表达式将不匹配的主要内容,如果未能解决你的问题,请参考以下文章