C# 查找并替换自定义标记

C# 查找并替换自定义标记,c#,regex,C#,Regex,我有一些输入字符串,比如 <Parameters><job>true</job><BeginDate>August2017</BeginDate><processed>true</processed></Parameters> 我能够找到2017年8月,并用实际日期替换,但我无法将其替换为原始日期 Match match = Regex.Match(customDate, @"<BeginDa

我有一些输入字符串,比如

<Parameters><job>true</job><BeginDate>August2017</BeginDate><processed>true</processed></Parameters>
我能够找到2017年8月,并用实际日期替换,但我无法将其替换为原始日期

Match match = Regex.Match(customDate, @"<BeginDate>([A-Za-z0-9\-]+)\<\/BeginDate>", RegexOptions.IgnoreCase);
if (match.Success)
{
    string key = match.Groups[1].Value;
    var newDate = DateTime.ParseExact(key, "MMMMyyyy", System.Globalization.CultureInfo.InvariantCulture);

    ???? how to replace newDate back to original ????
}
Match Match=Regex.Match(customDate,@“([A-Za-z0-9\-]+)\”,RegexOptions.IgnoreCase);
如果(匹配成功)
{
字符串键=匹配。组[1]。值;
var newDate=DateTime.ParseExact(键“MMMMyyyy”,System.Globalization.CultureInfo.InvariantCulture);
??如何将新日期替换回原始日期????
}

您可以在替换中使用预期的原始格式

customDate = customDate.Replace(newDate.ToString("MMMMyyyy"), newDate.ToString("MM/dd/yyyy"));
考虑另一种方法来处理似乎是XML的内容:

var xe = System.Xml.Linq.XElement.Parse(customDate);
if(DateTime.TryParseExact(xe.Element("BeginDate").Value, "MMMMyyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.NoCurrentDateDefault, out var newDate))
{
    xe.Element("BeginDate").Value = newDate.ToString("MM/dd/yyyy");
}
然后,您可以使用以下方法取回字符串:

xe.ToString(System.Xml.Linq.SaveOptions.DisableFormatting)

您可以在替换中使用预期的原始格式

customDate = customDate.Replace(newDate.ToString("MMMMyyyy"), newDate.ToString("MM/dd/yyyy"));
考虑另一种方法来处理似乎是XML的内容:

var xe = System.Xml.Linq.XElement.Parse(customDate);
if(DateTime.TryParseExact(xe.Element("BeginDate").Value, "MMMMyyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.NoCurrentDateDefault, out var newDate))
{
    xe.Element("BeginDate").Value = newDate.ToString("MM/dd/yyyy");
}
然后,您可以使用以下方法取回字符串:

xe.ToString(System.Xml.Linq.SaveOptions.DisableFormatting)

你有XML。为什么不使用设计用于处理XML的东西,而不是将其视为字符串呢?我只展示了部分字符串。它不是真正的XML,而是带有类似XML的标记的字符串。为什么不使用设计用于处理XML的东西,而不是将其视为字符串呢?我只展示了部分字符串。它不是实际的XML,而是带有类似XML标记的字符串。如果您添加一点说明,可能会对OP有所帮助,也许您可以描述为什么不使用正则表达式而使用XDocument DOM函数。如果您添加一点说明,可能会对OP有所帮助,也许您可以描述为什么不使用正则表达式而使用XDocument DOM函数。