Search code examples
vb.netstringtrim

Trim a string - remove space and parentheses in VB.NET


Would someone help me with this please?

In vb.net (VS2013): a string is in the format: char12345 (6789).jpg

trim to the string to: char12345.jpg

Basically, I need to trim off the middle part: the space and everything in parentheses (including the parentheses).

will VB's trim function work? or I need to use RegEx...

Many thanks in advance!


Solution

  • You don't need regex, you could remove the parantheses also with pure string methods:

    Dim path = "char12345 (6789).jpg"
    Dim ext = IO.Path.GetExtension(path)
    Dim fn = IO.Path.GetFileNameWithoutExtension(path)
    Dim index = fn.IndexOf("(")
    If index >= 0 Then fn = fn.Remove(index).Trim()
    path = String.Format("{0}{1}", fn, ext)
    

    Presumes that they are always directly before the extension or that the part behind them can also be removed. Otherwise it's getting a little bit more complicated:

    Dim index = fn.IndexOf("(")
    If index >= 0 Then
        Dim endindex = fn.LastIndexOf(")", index)
        If endindex >= 0 Then
            fn = fn.Remove(index).Trim() & fn.Substring(endindex + 1)
        Else
            fn = fn.Remove(index).Trim()
        End If
    End If