文件模式的Regex

本文关键字:Regex 模式 文件 | 更新日期: 2023-09-27 17:57:47

我有一个类似Sample File_20140408201420(20140409_0).xlsx 的文件名

我在C#代码中将模式设置为'Sample File'+ @"(.*)'.xlsx",但正则表达式匹配不起作用。20140408201420(20140409_0)是将根据文件名进行更改的部分。

我应该使用什么是正确的Regex模式?

文件模式的Regex

试试这个正则表达式:

static Regex rxFileNamePattern = new Regex( @"
  ^           # anchor the match at start-of-text, followed by
  Sample File # the literal "Sample File", followed by
  'd+         # 1 or more decimal digits, followed by
  '(          # a literal left/open parenthesis "(", followed by
  'd+         # 1 or more decimal digits, followed by
  _           # a literal underscore "_", followed by
  'd+         # 1 or more decimal digits, followed by
  ')          # a literal right/close parenthesis ")", followed by
  '.xlsx      # the literal ".xlsx", followed by
  $           # end-of-text
  " , RegexOptions.IgnorePatternWhitespace ) ;
using System;
using System.Text.RegularExpressions;
class Program
{
    static void Main()
    {
    // First we see the input string.
    string input = "Sample File_20140408201420(20140409_0).xlsx";
    // Here we call Regex.Match.
    Match match = Regex.Match(input, @"Sample File_(.*)'.xlsx",
        RegexOptions.IgnoreCase);
    // Here we check the Match instance.
    if (match.Success)
    {
        // Finally, we get the Group value and display it.
        string key = match.Groups[1].Value;
        Console.WriteLine(key);
    }
    }
}

我做了什么?

我已将正则表达式更改为:

@"Sample File_(.*)'.xlsx"

这将返回值:

20140408201420(20140409_0)

我想这就是你想要的

您可以尝试此Regex:

var matches = Directory.GetFiles(@"c:'temp").Where(path => Regex.Match(path, @"Sample File_[0-9]{14}(.*)'.xlsx").Success);

如果你不在乎数量,你可以试试这个:

var matches = Directory.GetFiles(@"c:'temp").Where(path => Regex.Match(path, @"Sample File_(.*)'.xlsx").Success);