我有这个网址:
http://www.website.com/base.htm?age=<number>&Team=<number>&userID=<number>
如何将其中的部分内容放入文本框?
即:
Textbox1 = number after ?age=
Textbox2 = number after &Team=
Textbox3 = number after &userID=
答案 0 :(得分:2)
Dim url As String = "http://www.website.com/base.htm?age=15&Team=100&userID=1109"
Dim temp As String = url.Substring(url.IndexOf("?")+1)
Dim args() As String
args = temp.Split("&")
Dim pair() As String
For Each arg As String In args
pair = arg.Split("=")
console.WriteLine(pair(0))
console.WriteLine(pair(1)) ' <--- value after =
Next
答案 1 :(得分:2)
如果您想输出到TextBox
并且可以保证一定数量的参数,这很简单:
Dim url As String = "http://www.website.com/base.htm?age=15&Team=3&userID=1"
TextBox1.Text = url.Split("?"c)(1).Split("&"c)(0).Split("="c)(1)
TextBox2.Text = url.Split("?"c)(1).Split("&"c)(1).Split("="c)(1)
TextBox3.Text = url.Split("?"c)(1).Split("&"c)(2).Split("="c)(1)
代码看起来有点难以理解,但它完成了这项工作。请注意第二个Split
上的数字增加。这是输出:
现在我要做的是进一步检查以确保参数在那里并且它们具有值:
Dim url As String = "http://www.website.com/base.htm?age=15&Team=3&userID=1"
Dim parameters As String = Nothing
If url.Contains("?") Then
parameters = url.Split("?"c)(1)
End If
Dim age As Integer = 0
Dim team As Integer = 0
Dim userId As Integer = 0
If parameters IsNot Nothing Then
For Each parameter In parameters.Split("&"c)
If parameter.Contains("=") Then
If parameter.ToLower().StartsWith("age") Then
Integer.TryParse(parameter.Split("="c)(1), age)
ElseIf parameter.ToLower().StartsWith("team") Then
Integer.TryParse(parameter.Split("="c)(1), team)
ElseIf parameter.ToLower().StartsWith("userid") Then
Integer.TryParse(parameter.Split("="c)(1), userId)
End If
End If
Next
End If
TextBox1.Text = age.ToString()
TextBox2.Text = team.ToString()
TextBox3.Text = userId.ToString()
输出与上面相同但我做了进一步的检查。我确信可以进行更多检查,但我认为这会给你一个良好的开端。
我喜欢做的是使用Dictionary存储参数的名称和值,这可以派上用场,所以我想我会告诉你这个方法:
Dim url As String = "http://www.website.com/base.htm?age=<number>&Team=<number>&userID=<number>"
Dim urlParameters As New Dictionary(Of String, String)
If url.Contains("?") AndAlso url.Contains("&") Then
For Each param In url.Split("?"c)(1).Split("&"c)
Dim kp() As String = param.Split("="c)
urlParameters.Add(kp(0), kp(1))
Next
End If
'ouput
For Each parameter In urlParameters
Debug.WriteLine("Key: " & parameter.Key & " Value:" & parameter.Value)
Next
这是输出的屏幕截图:
如果您只想查看参数和输出的值,那么您只需执行此操作而不是添加到Dictionary
:
If url.Contains("?") AndAlso url.Contains("&") Then
For Each param In url.Split("?"c)(1).Split("&"c)
Debug.WriteLine(param.Split("="c)(1))
Next
End If
在这种情况下,输出将是: