拆分URL分为两部分(字符串)

时间:2013-03-14 16:17:31

标签: regex vb.net

我正在尝试找到一种方法来轻松地将路径(原始URL)拆分为两部分: 例如:/ search / criteria / newyork / list

我想在第三个斜杠之前填充一个包含所有内容的字符串,在这种情况下:“/ search / criteria” 我还想把第二部分变成一个字符串:“newyork / list”

4 个答案:

答案 0 :(得分:1)

试试这个:

Dim sAux() As String = sURL.Split("/"c)
Dim sResult As String = ""

If sAux.Length > 3 Then
    For i As Integer = 2 to sAux.Length - 1
        sResult &= sAux(i) & "/"
    Next
End If

或者这个:

Dim sAux As New List(Of String)(sURL.Split("/"c))
sAux.RemoveRange(0,2)    

sResult = String.Join("/", sAux.ToArray())

答案 1 :(得分:1)

您可以使用IndexOf查找第三个斜杠(假设第一个字符始终是第一个斜杠,并且字符串中至少有三个斜杠):

Dim index3 = url.IndexOf("/"c, url.IndexOf("/"c, 1) + 1)

然后你可以使用Substring来获取斜杠之前和之后的部分:

Dim path As String = url.Substring(0, index3)
Dim resource As String = url.Substring(index3 + 1)

答案 2 :(得分:0)

        Dim ar As String()
        Dim str1 As String
        Dim str2 As String
        Dim a As Integer
        Dim splitPosition = 3
        Dim urlToSplit = "/search/criteria/newyork/list"
        ar = urlToSplit.Split("/"c)

        If UBound(ar) < splitPosition Then
            ' there are 3 or less slashes. do what you want here, error or just exit
        Else
            For a = 0 To splitPosition - 1
                If Not String.IsNullOrEmpty(ar(a)) Then str1 += ar(a) + "/"
            Next
            For a = splitPosition To UBound(ar)
                If Not String.IsNullOrEmpty(ar(a)) Then str2 += ar(a) + "/"
            Next
        End If

str1将包含/search/criteria/ str2将包含newyork/list/

此代码将处理任意数量的/组合,并且不应为错误形成的Url错误输出

答案 3 :(得分:0)

如果您的字符串始终采用相同的格式且具有相同数量的元素(在拆分数组中),则可以使用String.Format方法;

Dim arr() As String =  "/search/criteria/newyork/list".Split("/"c)
Dim str1 As String = String.Format("/{1}/{2}", arr) '/search/criteria
Dim str2 As String = String.Format("{3}/{4}", arr) 'newyork/list