如何使用c#查找字符串上的dd/mm/yyyy日期
本文关键字:dd mm yyyy 日期 何使用 查找 字符串 | 更新日期: 2023-09-27 18:18:35
我有一个文件,我想替换日期,但我不知道日期是什么,我想为我做通用代码,为其他文件使用相同的可执行文件。
我把文件的所有内容放在一个字符串中,我想用dd/mm/yyyy(例如:19/12/2011)的格式替换所有日期,并使用实际日期(20/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 "";
}
}
}
这是一个使用MatchEvaluator的解决方案。如果需要,调整正则表达式;
string UpdateDates(string input)
{
return Regex.Replace(input, @"'d{2}/'d{2}/'d{4}", m => DateTime.Now.ToString("dd/MM/yyyy"));
}
您可以使用正则表达式http://www.regular-expressions.info/dates.html
使用包含原始文件布局的另一个文件,但在需要替换的日期中放置另一个字符串,例如"DD/MM/YYYY"。
现在,您只需要打开布局文件,读取所有内容,将"DD/MM/YYYY"替换为您想要的日期和voil