C# 月、日和年的正则表达式反向引用?

C# 月、日和年的正则表达式反向引用?,c#,regex,C#,Regex,我使用正则表达式语句来匹配文件名中的日期。我想将输出分成几个组(我的语句就是这样做的) 到目前为止,我已经测试了输出,但我似乎无法将组值传递到字符串,以便使用它们创建目录。事实上,我似乎根本无法理解我的团队价值观 我知道这可以在没有正则表达式的情况下完成,但我选择了这种方式来尝试和学习它。我的输入字符串是一个文件名“Result5\u 14\u 20009 1\u 30\u 00 PM.xml” 如何创建字符串“month”,将值传递给组1等 以下是我到目前为止的情况: private void

我使用正则表达式语句来匹配文件名中的日期。我想将输出分成几个组(我的语句就是这样做的)

到目前为止,我已经测试了输出,但我似乎无法将组值传递到字符串,以便使用它们创建目录。事实上,我似乎根本无法理解我的团队价值观

我知道这可以在没有正则表达式的情况下完成,但我选择了这种方式来尝试和学习它。我的输入字符串是一个文件名
“Result5\u 14\u 20009 1\u 30\u 00 PM.xml”

如何创建字符串
“month”
,将值传递给组1等

以下是我到目前为止的情况:

private void btnSort_Click(object sender, EventArgs e)
{
    string fileName = "Result*.xml";
    string sourcePath = txtSource.Text;
    string targetPath = txtDest.Text;

    //Get Data from Filename
    string[] files = System.IO.Directory.GetFiles(sourcePath);
    Regex date = new Regex(@"([1-9]|[0-2])_(\d{2})_(\d{4})", RegexOptions.CultureInvariant);

    foreach (string s in files)
    {
        Match m = date.Match(s);
        if (m.Success)
        {
            //Pass Groups to String

            //Create Dir for Group 3 (Year) 
            //Create Dir for Group 1 (Month)
            //Create Dir for Group 2 (Day)
        }
    }
}

就快到了,只需在正则表达式中定义组:

Regex date = new Regex(@"(?<MONTH>[1-9]|[0-2])_(?<DAY>\d{2})_(?<YEAR>\d{4})", RegexOptions.CultureInvariant);

foreach(Match oMatch in oMatchCollection) 
{ 

 Console.WriteLine("MONTH: "+oMatch.Groups["MONTH"].Value);
 Console.WriteLine("DAY: "+oMatch.Groups["DAY"].Value); 
 Console.WriteLine("YEAR: "+oMatch.Groups["YEAR"].Value); 
} 
Regex-date=newregex(@“(?[1-9]|[0-2])(?\d{2})(?\d{4})”,RegexOptions.CultureInvariant);
foreach(在oMatchCollection中匹配oMatch)
{ 
Console.WriteLine(“月:+oMatch.Groups[“月”].Value);
Console.WriteLine(“日:+oMatch.Groups[“日”].Value);
Console.WriteLine(“年:+oMatch.Groups[“年”].Value);
} 

您可以通过访问组,也可以通过访问组值。要将组值组合到路径中,可以使用。要创建目录,您可以使用:


您正在查找
匹配对象的
属性。要继续您的示例,请执行以下操作:

if (m.Success)
{
    //groups[0] will be the entire filename
    string year = m.Groups[3].Value;
    string month = m.Groups[1].Value;
    string day = m.Groups[2].Value;

    //create dirs...
}
我曾多次访问过一个网站来测试.NET正则表达式的行为,这个网站是:,它向您展示了在给定示例输入和正则表达式的情况下,您将得到哪些组


希望能有帮助。

我会这样做的。我正在重命名这些文件,因为我希望我的文件名能够正确地整理

static void OrganizeFiles( DirectoryInfo src , DirectoryInfo tgt )
{
  foreach ( FileInfo file in src.EnumerateFiles("result*.xml") )
  {
    Match m = FileNamePatternRegex.Match( file.Name ) ;
    bool processed = false ;
    if ( m.Success)
    {
      string datetime = m.Groups["datetime"].Value ;
      DateTime resultDate ;
      bool parseSucceeded = DateTime.TryParseExact( datetime , "M_d_yyyy h_m_s tt" , CultureInfo.InvariantCulture , DateTimeStyles.AllowWhiteSpaces , out resultDate ) ;
      if ( parseSucceeded )
      {
        DirectoryInfo subDir = tgt.CreateSubdirectory( resultDate.ToString(  @"yyyy\MM\dd" ) ) ;
        string newName     = resultDate.ToString( "result.yyyy-MM-ddTHH:mm:ss.xml" ) ;
        string destination = Path.Combine( subDir.FullName , newName ) ;
        file.MoveTo( destination ) ;
        processed = true ;
      }
    }
    if ( !processed )
    {
      Console.WriteLine( "skipping file {0}" , file.FullName ) ;
    }
  }
  return ;
}
const string          FileNamePattern      = @"^result(?<datetime>\d+_\d+_\d+ +\d+_\d+_\d+ +(am|pm))\.xml" ;
static readonly Regex FileNamePatternRegex = new Regex( FileNamePattern , RegexOptions.IgnoreCase|RegexOptions.ExplicitCapture ) ;
静态无效组织文件(DirectoryInfo src、DirectoryInfo tgt)
{
foreach(src.EnumerateFiles(“result*.xml”)中的FileInfo文件)
{
Match m=FileNamePatternRegex.Match(file.Name);
bool-processed=false;
如果(m.成功)
{
字符串datetime=m.Groups[“datetime”].Value;
日期时间结果日期;
bool parsesucceed=DateTime.TryParseExact(DateTime,“M_d_yyy h_M_s tt”,CultureInfo.InvariantCulture,datetimestyle.AllowWhiteSpaces,out resultDate);
如果(解析成功)
{
DirectoryInfo subDir=tgt.CreateSubdirectory(resultDate.ToString(@“yyy\MM\dd”);
字符串newName=resultDate.ToString(“result.yyy-MM-ddTHH:MM:ss.xml”);
string destination=Path.Combine(subDir.FullName,newName);
file.MoveTo(目的地);
已处理=真;
}
}
如果(!已处理)
{
WriteLine(“跳过文件{0}”,file.FullName);
}
}
返回;
}
常量字符串FileNamePattern=@“^result(?\d++\ud++\ud++\d++\ud++(am | pm))\.xml”;
静态只读Regex FileNamePatternRegex=newregex(FileNamePattern,RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);

这就是我的砖墙。谢谢。完整的例子帮助我解决了不相关的问题!thnx为什么我在vs中得到“字符串不包含定义”错误,根据我刚才读取的path的参数1。联合方法必须是绝对路径。在这种情况下,我有一个文件夹浏览器对话框来选择或创建根目录。关于如何继续使用此方法的任何想法。字符串路径=路径。组合(,m.Groups[3]。Value,m.Groups[1]。Value,m.Groups[2]。Value);
static void OrganizeFiles( DirectoryInfo src , DirectoryInfo tgt )
{
  foreach ( FileInfo file in src.EnumerateFiles("result*.xml") )
  {
    Match m = FileNamePatternRegex.Match( file.Name ) ;
    bool processed = false ;
    if ( m.Success)
    {
      string datetime = m.Groups["datetime"].Value ;
      DateTime resultDate ;
      bool parseSucceeded = DateTime.TryParseExact( datetime , "M_d_yyyy h_m_s tt" , CultureInfo.InvariantCulture , DateTimeStyles.AllowWhiteSpaces , out resultDate ) ;
      if ( parseSucceeded )
      {
        DirectoryInfo subDir = tgt.CreateSubdirectory( resultDate.ToString(  @"yyyy\MM\dd" ) ) ;
        string newName     = resultDate.ToString( "result.yyyy-MM-ddTHH:mm:ss.xml" ) ;
        string destination = Path.Combine( subDir.FullName , newName ) ;
        file.MoveTo( destination ) ;
        processed = true ;
      }
    }
    if ( !processed )
    {
      Console.WriteLine( "skipping file {0}" , file.FullName ) ;
    }
  }
  return ;
}
const string          FileNamePattern      = @"^result(?<datetime>\d+_\d+_\d+ +\d+_\d+_\d+ +(am|pm))\.xml" ;
static readonly Regex FileNamePatternRegex = new Regex( FileNamePattern , RegexOptions.IgnoreCase|RegexOptions.ExplicitCapture ) ;