查找并替换自定义标记

时间:2017-10-24 19:51:59

标签: c# regex

我有一些像

这样的输入字符串
<Parameters><job>true</job><BeginDate>August2017</BeginDate><processed>true</processed></Parameters>

我必须提取BeginDate值并将其替换为实际的日期时间值。所以输出应该看起来像

<Parameters><job>true</job><BeginDate>08/01/2017</BeginDate><processed>true</processed></Parameters>

我能够找到August2017并将其替换为实际日期,但我无法将其替换为原始日期。

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 ????
}

2 个答案:

答案 0 :(得分:1)

var xDoc = XDocument.Parse(inputString);
var BeginDate = xDoc.Descendants("BeginDate").First();
BeginDate.Value = "08/08/2017";
var outputString = xDoc.ToString();

答案 1 :(得分:1)

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

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)
相关问题