How to remove comments from a string in VB.NET

1 Answer

0 votes
Imports System

Module Module1

    Function RemoveSingleLineComments(input As String) As String
        Dim result As New Text.StringBuilder()

        For Each line In input.Split({Environment.NewLine}, StringSplitOptions.None)
            Dim pos = line.IndexOf("'"c)
            If pos >= 0 Then
                result.AppendLine(line.Substring(0, pos))
            Else
                result.AppendLine(line)
            End If
        Next

        Return result.ToString()
    End Function

    Sub Main()
        Dim text As String =
"Dim x = 10 ' this is a comment
Dim y = 20
Dim z = x + y ' another comment"

        Dim cleaned = RemoveSingleLineComments(text)

        Console.WriteLine(cleaned)
    End Sub

End Module



' run:
'
' Dim x = 10 
' Dim y = 20
' Dim z = x + y 
'

 



answered 1 day ago by avibootz
...