使用正则表达式替换文件

时间:2014-01-03 04:56:02

标签: .net regex vb.net visual-studio-2010

我试图替换月份标签的内部文本,即月份名称应替换为其指定的月份编号。 我试过这个,

 Dim strFile As String = File.ReadAllText(TextBox1.Text & "\" & parentFolder & ".xml")
    strFile = Regex.Replace(strFile, "<conf-start iso-8601-date=""([0-9-]+)""><day>([0-9]+)</day><month>March</month>", "<conf-start iso-8601-date=""([0-9-]+)""><day>([0-9]+)</day><month>03</month>")
    File.WriteAllText(TextBox1.Text & "\" & parentFolder & ".xml", strFile)

现在的问题是,如果这条线是这样的,

<conf-start iso-8601-date="2011-03-06"><day>06</day><month>March</month><year>2011</year></conf-start>

这里上面的表达式是捕获数据并将其替换为

<conf-start iso-8601-date=""([0-9-]+)""><day>([0-9-]+)</day><month>03</month><year>2011</year></conf-start>
而是应该替换

<conf-start iso-8601-date="2011-03-06"><day>06</day><month>03</month>

任何帮助都会得到真正的褒奖

2 个答案:

答案 0 :(得分:1)

试试这个

Dim y = "<conf-start iso-8601-date=""2011-05-31""><day>31</day><month>Jan</month><year>2011</year></conf-start>"

Dim Match = Regex.Match(y, "<month>([^>]*)<\/month>").Groups(1).ToString
Regex.Replace(y, Match, DateTime.ParseExact(Match, "MMM", CultureInfo.CurrentCulture).Month.ToString)

它会给你OP赞

<conf-start iso-8601-date="2011-05-31"><day>31</day><month>01</month><year>2011</year></conf-start>

答案 1 :(得分:1)

你可以这样做:

Dim doc As New XmlDocument()
Dim months As IDictionary(Of String, String) = New Dictionary(Of String, String)() From {{"January", "1"}, {"February", "2"}, {"March", "3"}, {"April", "4"}, {"May", "5"}, {"June", "6"}, {"July", "7"}, {"8", "August"}, {"September", "9"}, {"October", "10"}, {"November", "11"}, {"December", "12"}}
Dim expr As New Regex([String].Join("|", months.Keys))
Dim strFile As String = "May"

doc.Load(TextBox1.Text & "\" & parentFolder & ".xml")

For Each item As XmlNode In doc.GetElementsByTagName("month")
    item.Value = expr.Replace(item.Value, Function(m) months(m.Value))
Next