【问题标题】:VBScript Replace specific value with regex and modify text fileVBScript 用正则表达式替换特定值并修改文本文件
【发布时间】:2016-04-14 17:28:08
【问题描述】:

我知道有很多类似的问题,但我找不到适合我的答案。我需要替换 xml 文件中以 % 开头和结尾的所有短语(例如 %TEST%%TEST-NEW%

到目前为止,我有这些试用: 这是我在控制台中工作的测试,但只有 1 行字符串

zone = "<test>%TEST%</test>"
MsgBox zone
'Setting the regex and cheking the matches
set regex = New RegExp
regex.IgnoreCase = True
regex.Global = True
regex.Pattern = "%.+%"
Set myMatches = regex.execute(zone)
For each myMatch in myMatches
Wscript.echo myMatch
result = Replace(zone,myMatch,"")
next
MsgBox result

但是当我尝试用这个文件从一个文件中做同样的事情时......

Dim objStream, strData, fields
Set objStream = CreateObject("ADODB.Stream")
objStream.CharSet = "utf-8"
objStream.Open
objStream.LoadFromFile("C:\test\test.xml")
strData = objStream.ReadText()
Wscript.echo strData

set regex = New RegExp
regex.IgnoreCase = True
regex.Global = True
regex.Pattern = "%.+%"
Set myMatches = regex.execute(strData)
For each myMatch in myMatches
Wscript.echo myMatch
result = Replace(strData,myMatch,"")
next
Wscript.echo result

...第一个回显正确返回文件的包含,然后循环中的第二个回显回显我需要替换的所有匹配项,但最后一个回显返回与第一个相同的结果(没有被替换)

xml 看起来像这样(仅作为示例):

<script>%TEST%</script>
<value>%VALUE%</value>
<test>%TEST%</test>

附:我需要遍历特定文件夹中的 xml 文件并替换上面的短语。有人可以帮忙吗?

适合我的最终脚本(非常感谢Tomalak):

Option Explicit

Dim path, doc, node, placeholder,srcFolder,FSO,FLD,fil

Set placeholder = New RegExp
placeholder.Pattern = "%[^%]+%"
placeholder.Global = True


srcFolder = "C:\test"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set FLD = FSO.GetFolder(srcFolder)

For each fil In FLD.Files

    if LCase(FSO.GetExtensionName(fil.Name)) = "xml" Then

            path = "C:\test\" & fil.Name

            ' 1. parse the XML into a DOM
            Set doc = LoadXmlDoc(path)

            ' 2. select and modify DOM nodes
            For Each node In doc.selectNodes("//text()|//@*")
                node.nodeValue = SubstitutePlaceholders(node.nodeValue)
            Next

            ' 3. save modified DOM back to file
            doc.save path
    End If

Next            
' --------------------------------------------------------------------------

Function LoadXmlDoc(path)
    Set LoadXmlDoc = CreateObject("MSXML2.DomDocument.6.0")

    LoadXmlDoc.async = False
    LoadXmlDoc.load path
    If LoadXmlDoc.parseError.errorCode <> 0 Then
        WScript.Echo "Error in XML file."
        WScript.Echo LoadXmlDoc.parseError.reason
        WScript.Quit 1
    End If
End Function
' --------------------------------------------------------------------------

Function SubstitutePlaceholders(text)
    Dim match

    For Each match In placeholder.Execute(text)
        text = Replace(text, match, GetReplacement(match))
    Next

    SubstitutePlaceholders = text
End Function
' --------------------------------------------------------------------------

Function GetReplacement(placeholder)
    Select Case placeholder
        Case "%TEST%": GetReplacement = "new value"
        Case "%BLA%": GetReplacement = "other new value"
        Case Else: GetReplacement = placeholder
    End Select
End Function
' --------------------------------------------------------------------------

【问题讨论】:

    标签: vbscript


    【解决方案1】:

    永远不要对 XML 文件使用正则表达式,句号。

    使用 XML 解析器。它会更简单,代码会更容易阅读,最重要的是:它不会破坏 XML。

    以下是如何以正确的方式修改您的 XML 文档。

    Option Explicit
    
    Dim path, doc, node, placeholder
    
    Set placeholder = New RegExp
    placeholder.Pattern = "%[^%]+%"
    placeholder.Global = True
    
    path = "C:\path\to\your.xml"
    
    ' 1. parse the XML into a DOM
    Set doc = LoadXmlDoc(path)
    
    ' 2. select and modify DOM nodes
    For Each node In doc.selectNodes("//text()|//@*")
        node.nodeValue = SubstitutePlaceholders(node.nodeValue)
    Next
    
    ' 3. save modified DOM back to file
    doc.save path
    ' --------------------------------------------------------------------------
    
    Function LoadXmlDoc(path)
        Set LoadXmlDoc = CreateObject("MSXML2.DomDocument.6.0")
    
        LoadXmlDoc.async = False
        LoadXmlDoc.load path
        If LoadXmlDoc.parseError.errorCode <> 0 Then
            WScript.Echo "Error in XML file."
            WScript.Echo LoadXmlDoc.parseError.reason
            WScript.Quit 1
        End If
    End Function
    ' --------------------------------------------------------------------------
    
    Function SubstitutePlaceholders(text)
        Dim match
    
        For Each match In placeholder.Execute(text)
            text = Replace(text, match, GetReplacement(match))
        Next
    
        SubstitutePlaceholders = text
    End Function
    ' --------------------------------------------------------------------------
    
    Function GetReplacement(placeholder)
        Select Case placeholder
            Case "%TEST%": GetReplacement = "new value"
            Case "%BLA%": GetReplacement = "other new value"
            Case Else: GetReplacement = placeholder
        End Select
    End Function
    ' --------------------------------------------------------------------------
    

    XPath 表达式//text()|//@* 以所有文本节点和所有属性节点为目标。如有必要,请使用不同的 XPath 表达式。 (我不会在这里介绍 XPath 基础知识,有很多资源可供学习。)

    当然,此解决方案使用正则表达式,但它是针对 XML 结构包含的文本值执行此操作,而不是针对 XML 结构本身。这是一个至关重要的区别。

    【讨论】:

    • 它适用于一个文件,但是让它循环通过文件夹中的所有 xml 文件的最佳方法是什么?
    • 好吧。从修改单个文件的部分中创建一个函数,在 For Each 循环中运行该函数。 FileSystemObject 将帮助您进行文件系统操作。
    • 我让它循环遍历文件(你可能会这样做更丑,但它可以工作),现在我有一个问题,如果文件夹中有其他文件类型,脚本会崩溃。任何想法如何只处理 .xml 文件?
    • 在处理文件之前检查文件扩展名。在 VBScript 中有多种检查文件扩展名的方法,请选择一种适合您的方法。
    • @changer 好了! - 我刚刚看到你的问题的编辑。这也正是我会做的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    • 2011-09-05
    • 2017-10-18
    • 2014-03-11
    • 2017-07-12
    相关资源
    最近更新 更多