使用正则表达式替换文件 [英] Replacing file using regex

查看:183
本文介绍了使用正则表达式替换文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图取代月份标签即月名称内部文本应替换其规定月份数。 我想这一点,

i tried to replace inner text of the month tag i.e 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>

下面上述EX pression被捕获的数据,并用其替换,

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>

任何帮助将真正aprreciated

any help will be really aprreciated

推荐答案

您可以做到这一点是这样的:

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

这篇关于使用正则表达式替换文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆