MrNeedsaHand
MrNeedsaHand

Reputation: 45

Cannot trim closed bracket from vb.net string

I have an issue trimming a string in vb.net

Dim bgColor1 As String = (foundRows(count).Item(16).ToString()) 

'This returns Color [Indigo] I need it to be just Indigo so vb.net can read it.

'So i used this

Dim MyChar() As Char = {"C", "o", "l", "r", "[", "]", " "}
Dim firstBgcolorbgColor1 As String = bgColor1.TrimStart(MyChar)

'But the ] is still in the string so it looks like this Indigo]

Any ideas on why i cannot trim the ]?

Upvotes: 1

Views: 273

Answers (4)

Shar1er80
Shar1er80

Reputation: 9041

Update

Didn't see that the input was "Color [Indigo]". I would not recommend TrimStart() & TrimEnd()

You have a variety of options to choose from:

Imports System
Imports System.Text.RegularExpressions

Public Module Module1
    Public Sub Main()
        Dim Color As String = "Color [Indigo]"

        ' Substring() & IndexOf()
        Dim openBracket = Color.IndexOf("[") + 1
        Dim closeBracket = Color.IndexOf("]")
        Console.WriteLine(Color.Substring(openBracket, closeBracket - openBracket))

        ' Replace()
        Console.WriteLine(Color.Replace("Color [", String.Empty).Replace("]", String.Empty))

        ' Regex.Replace()
        Console.WriteLine(Regex.Replace(Color, "Color \[|\]", String.Empty))

        ' Regex.Match()
        Console.WriteLine(Regex.Match(Color, "\[(\w+)\]").Groups(1)) 
    End Sub
End Module

Results:

Indigo
Indigo
Indigo
Indigo

Demo

Upvotes: 2

Meta-Knight
Meta-Knight

Reputation: 17845

You could use a Regex to do the job:

Dim colorRegex As New Regex("(?<=\[)\w+") 'Get the word following the bracket ([)

Dim firstBgcolorbgColor1 As String = colorRegex.Match(bgColor1).Value

Upvotes: 1

hyde
hyde

Reputation: 2585

The TrimStart, TrimEnd, and Trim functions remove spaces from beginning, end and both side of the strings respectively. You are using TrimStart to remove any leading the spaces but it is leaving white space is at the end. So you need to use Trim. Trim won't remove anything else than white space characters, so your ] character will still appear in the final string. You need to do String.Remove to remove characters you don't want.

Examples here: http://www.dotnetperls.com/remove-vbnet

Upvotes: -1

sstan
sstan

Reputation: 36473

Well, you are calling TrimStart(...), which as the name implies, will only trim the front part of the string.

Did you mean to call Trim(MyChar) instead?

Upvotes: 1

Related Questions