繁体   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