简体   繁体   中英

Trim a string from a specific character on

I've got a textbox, its text property is a path such as this, for example:

/users/me/whatever

What I want is to delete the last "folder" and have this:

/users/me

I've tried things with the trim and split functions but for now I'm not achieving what I want.

edit:

Private Sub btn_Back_Click(sender As Object, e As EventArgs) Handles btn_Back.Click

    If Not (txt_Path.Text = "/") Then
        txt_Path.Text = ... ?
    End If

End Sub

Can anyone help? Thanks

您可以尝试Path.GetDirectoryName

txt_Path.Text = Path.GetDirectoryName(txt_Path.Text)

It is pretty simple:

Dim str = txt_Path.Text
Dim i = str.LastIndexOf("/")
If i <> -1 then
   txt_Path.Text = str.Substring(0, i)
End if

You can also parse this using a regular expression :

Dim dir As String

' this may not work as expected if a user ends the directory with as slash, try it to see and then decide if that is ok or not?
' this regex pattern keeps everything except "everything that follows the last slash"
dir = Regex.Replace("/users/me/whatever", "^(.*)\/.*[^\/]$", "$1")
Console.WriteLine(dir)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM