How to remove parentheses and the text inside them from a string in VB.NET

2 Answers

0 votes
Imports System
Imports System.Text

Module Program

    ''' <summary>
    ''' Remove all parentheses and the text inside them.
    '''
    ''' @param text  The input string
    ''' @return      The cleaned string
    ''' </summary>
    Function RemoveParenthesesWithContent(text As String) As String
        Dim result As New StringBuilder()
        Dim depth As Integer = 0   ' Tracks whether we are inside parentheses

        ' Loop through each character
        For Each c As Char In text
            If c = "("c Then
                depth += 1         ' Enter parentheses
                Continue For
            End If

            If c = ")"c Then
                If depth > 0 Then depth -= 1   ' Exit parentheses
                Continue For
            End If

            If depth = 0 Then
                result.Append(c)   ' Only copy characters outside parentheses
            End If
        Next

        ' Trim extra spaces created after removal
        Dim cleaned As New StringBuilder()
        Dim space As Boolean = False

        For Each c As Char In result.ToString()
            If Char.IsWhiteSpace(c) Then
                If Not space Then cleaned.Append(" "c)
                space = True
            Else
                cleaned.Append(c)
                space = False
            End If
        Next

        ' Final trim of leading/trailing spaces
        Return cleaned.ToString().Trim()
    End Function

    Sub Main()
        Dim str As String = "(An) API (API) (is a) (connection) connects (between) computer programs"
        Dim output As String = RemoveParenthesesWithContent(str)

        Console.WriteLine(output)

    End Sub

End Module



'
' run:
'
' API connects computer programs
'

 



answered 2 days ago by avibootz
0 votes
Imports System
Imports System.Text.RegularExpressions


Module Program
	
	''' <summary>
	''' Remove all parentheses and the text inside them.
	'''
	''' @param text  The input string
	''' @return      The cleaned string
	''' </summary>
	Function RemoveParenthesesWithContent(text As String) As String
		' Remove parentheses and everything inside them
		Dim cleaned As String = Regex.Replace(text, "\([^)]*\)", " ")

		' Collapse multiple spaces into one 
		Dim collapsed As String = String.Join(" ", cleaned.Trim().Split({" "c, Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries))

		' Final trim of leading/trailing spaces
		Return collapsed.Trim()
	End Function
	
    Sub Main()
        Dim str As String = "(An) API (API) (is a) (connection) connects (between) computer programs"
        Dim output As String = RemoveParenthesesWithContent(str)

        Console.WriteLine(output)
    End Sub
End Module



'
' run:
'
' API connects computer programs
'

 



answered 2 days ago by avibootz

Related questions

...