Reputation: 45
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
Reputation: 9041
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
Upvotes: 2
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
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
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