2011-12-20 3 views
0

私は日付を置き換えたいファイルがありますが、どの日付が入っているのかわかりませんし、他のファイルに対して同じ実行可能ファイルを使用するための汎用コードを実行したいと思います。C#を使用して文字列のdd/mm/yyyyの日付を見つける方法は?

ファイルの内容をすべて文字列にして、すべての日付を実際の日付(2011年12月20日)のdd/mm/yyyy(例:19/12/2011)の形式に置き換えたいとします。


どうすればいいですか?


コードこれまで:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.IO; 

namespace ReplaceDates 
{ 
    class Program 
    { 
     static int Main(string[] args) 
     { 
      string FileIn = retreiveArgument(args, "i"); 
      int AddDays = Int32.Parse(retreiveArgument(args, "d")); 
      string date = (System.DateTime.Now).AddDays(AddDays).ToString("dd/MM/yyyy"); 

      string content = "", date2replace = ""; 

      if (File.Exists(FileIn)) 
      { 
       File.Copy(FileIn, FileIn + ".bkp", true); 
       try 
       { 
        content = File.ReadAllText(FileIn); 

        // here is what I need to do 
       } 
       catch (Exception) 
       { 
        Console.WriteLine("Error replacing dates in " + FileIn + "."); 
        return 0; 
       } 
       try 
       { 
        File.WriteAllText(FileIn, content); 
        Console.WriteLine("Dates replaced in " + FileIn + "."); 
        return 0; 
       } 
       catch (Exception) 
       { 
        Console.WriteLine("Couldn't write the file " + FileIn); 
        return 2; 
       } 
      } 
      else 
      { 
       Console.WriteLine("File " + FileIn + " does not exist."); 
       return 1; 
      } 
     } 



     private static string retreiveArgument(string[] argument, string argumentName) 
     { 
      for (int i = 0; i < argument.Length; i++) 
      { 
       if (argument[i].ToLower().Equals("-h") || argument[i].ToLower().Equals("help") || argument[i].ToLower().Equals("-help") || argument[i].Equals("?") || argument[i].Equals("-?")) 
       { 
        Console.WriteLine("Usage : "); 
        Console.WriteLine("ReplaceDates.exe -i [Input File] -d [Addition]"); 
        Console.WriteLine("[Input File] -> Complete path to the file."); 
        Console.WriteLine("[Addition] -> Adds the specified value in days to the actual date."); 
        Console.WriteLine(); 
        Console.WriteLine("This executable replaces the data from the input file."); 
       } 
       else 
       { 
        if (argument[i].Equals("-" + argumentName)) 
        { 
         return argument[i + 1].Trim(); 
        } 
       } 
      } 
      return ""; 
     } 
    } 
} 
+0

ファイル形式はありますか? –

+0

日付のフォーマットはmm/dd/yyyyはどうですか? 01/02/2012の内容をどのように伝えますか? – Ray

+0

@peer一般的なやり方でこれを行うことは考えていません。私は彼らが助けることができるかどうかを理解するために正規表現を探していましたが、まだ何もありませんでした。 –

答えて

1

を、レイアウトファイルを開き、すべてのコンテンツを読んで、あなたが日付のために、「DD/MM/YYYY」を交換して出来上がり:)する必要がある。ここMatchEvaluatorを使用したソリューションです。必要に応じて正規表現を微調整します。

string UpdateDates(string input) 
{ 
    return Regex.Replace(input, @"\d{2}/\d{2}/\d{4}", m => DateTime.Now.ToString("dd/MM/yyyy")); 
} 
+0

私はかなりいいと思われる私の鉱山を使用しました:) –

0

のための正規表現を使用することができます"DD/MM/YYYY"のような別の文字列を入力してください。

今、あなたは、単に

関連する問題