Othmane Hatiji
Othmane Hatiji

Reputation: 43

Remove what is second parentheses of a string vb.net

i have a string like this

blabla (lo-g) (kk-jj)

i want to make it like this

blabla (lo-g)

but when it's already like this in vb.net

blabla (lo-g) with one parenteses

just let it as and is

thanks

Upvotes: 0

Views: 146

Answers (3)

Nathan Champion
Nathan Champion

Reputation: 1312

Since you want to avoid RegEx, this is a simpler/easier to read version I think of what you're trying to accomplish with your loop through each character. Basically you split the string into an array using the ( character as the dividers. So, they need to be re-added but it's nominal since you only need the 1 included (or not).

Essentially splitting your string into this: "blabla (lo-g) (kk-jj)"

Array(0) = "blabla " Array(1) = "lo-g) "

So, Array(0) & "(" & Array(1) = "blabla (lo-g)", or simply returns the whole string if it counts <= 1 ( character

    Dim SplitText = text.Split("(")

    If SplitText.Length > 1 Then
        Return String.Format("{0}({1}", text.Split("(")(0), text.Split("(")(1))
        'This may be easier for you to read, though:
        'Return text.Split("(")(0) & "(" & text.Split("(")(1)
    End If

    Return text

Upvotes: 0

Othmane Hatiji
Othmane Hatiji

Reputation: 43

i want to thanks steven for his answer but for those who can't handle regex (like me) here's a simple stupid method

Dim res As String = String.Empty

        Dim check As Boolean = False

        For Each letter In teamname
            If letter = "(" Then
                If check = True Then
                    Exit For
                End If
                check = True
            End If
            res &= letter

        Next

        Return res

good luck

Upvotes: 1

Steven Doggart
Steven Doggart

Reputation: 43743

Regex is a powerful, flexible, and configurable tool for doing things like this. It's not entirely clear from your question exactly what rules need to be followed in other variations for the input, but here's an example which works for the inputs you specified:

Dim input As String = "blabla (lo-g) (kk-jj)"
Dim pattern As String = "(?<=^[^(]*\([^)]*\)\s*)\([^)]*\)(?=\s*$)"
Dim output As String = Regex.Replace(input, pattern, "")

However, that will not remove the second set of parenthesis for inputs like these:

blabla (lo-g) blabla (kk-jj) blabla
blabla (lo-g) (kk-jj) blabla

To handle variations like those, you could use a pattern like this:

Dim input As String = "blabla (lo-g) with (kk-jj) trailing"
Dim pattern As String = "(?<=^[^(]*\([^)]*\)[^(]*)\([^)]*\)(?=[^(]*$)"
Dim output As String = Regex.Replace(input, pattern, "")

Upvotes: 1

Related Questions