Find and Replace code between #region tags in .cs file

247 views Asked by At

I have a C# file called test.cs. It has a #region and #endregion declared for a section of code that I want to remove at a later date using VBScript through a batch file, and then save the contents out to a new file.

Here is my current attempt:

test.cs:

#region 

Console.WriteLine("test");

#endregion

Then in my VBScript file:

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

There are 1 answers

0
Ekkehard.Horner On BEST ANSWER

The pattern should look for a (possibly empty) sequence of 'everything' between #region and #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")

output:

cscript 30735491.vbs
a
x
x
a