簡體   English   中英

使用正則表達式替換文件

[英]Replacing file using regex

我試圖替換月份標簽的內部文本,即月份名稱應替換為其指定的月份號。 我試過了

 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>

任何幫助都會非常感激

嘗試這個

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>

您可以這樣做:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM