在.cs文件中的#region标记之间查找和替换代码

时间:2015-06-09 14:47:58

标签: c# vbscript

我有一个名为test.cs的C#文件。它为我想要在以后使用VBScript通过批处理文件删除的代码段声明了#region#endregion,然后将内容保存到新文件中。

这是我目前的尝试:

test.cs

#region 

Console.WriteLine("test");

#endregion

然后在我的VBScript文件中:

strInputFile  = "test.cs"
strOutputFile = "testOutput.cs"

Set fso = CreateObject("Scripting.FileSystemObject")

If fso.FileExists(strOutputFile) Then
  fso.DeleteFile strOutputFile
End If

strPattern = "(/#region/)(.|\s)*(/#endregion/)"
strReplaceString = "x"
strTestString = fso.OpenTextFile(strInputFile, 1).ReadAll
strNewText = fReplaceText(strPattern, strTestString, strReplaceString)
fso.OpenTextFile(strOutputFile, 2, True).WriteLine strTestString

Function fReplaceText(sPattern, sStr, sReplStr)
    Dim regEx, oMatch, colMatches, temp
    Set regEx = New RegExp     ' Create a regular expression.
    regEx.Pattern = sPattern   ' Set pattern.
    regEx.IgnoreCase = True    ' Set case insensitivity.
    regEx.Global = True        ' Set global applicability.

    Set colMatches = regEx.Execute(sStr)   ' Execute search.

    If colMatches.Count = 0 Then
        temp = ""
    Else
        For Each oMatch In colMatches
           temp = regEx.Replace(sStr, oMatch.SubMatches(0) & vbCrlf & sReplStr _
                  & vbCrlf & oMatch.SubMatches(2))
        Next
    End If
    fReplaceText = temp
End Function

1 个答案:

答案 0 :(得分:2)

模式应该在#region#endregion non-greedily之间寻找(可能为空)的“一切”序列:

Option Explicit

Dim r : Set r = New RegExp
r.Global  = True
r.Pattern = "#region[\s\S]*?#endregion"
WScript.Echo r.Replace(Join(Array( _
     "a" _
   , "#region#endregion" _
   , "#region" _
   , "a" _
   , "a" _
   , "#endregion" _
   , "a" _
), vbCrLf), "x")

输出:

cscript 30735491.vbs
a
x
x
a