简体   繁体   中英

Replacing file using regex

i tried to replace inner text of the month tag ie month names should be replaced with their specified month number. i tried this,

 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)

now the problem is that if the line is like this,

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

here the above expression is catching the data and replaces it with,

<conf-start iso-8601-date=""([0-9-]+)""><day>([0-9-]+)</day><month>03</month><year>2011</year></conf-start>

instead it should replace

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

any help will be really aprreciated

Try this

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)

It will give you OP Like

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

You could do it like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM