Vb.net 需要在'之后提取字符串@'&;在'之前';(空白)多次
我正在从一个文本框中提取twitter/facebook风格的提及。 到目前为止,我的代码如下:Vb.net 需要在'之后提取字符串@'&;在'之前';(空白)多次,vb.net,string,Vb.net,String,我正在从一个文本框中提取twitter/facebook风格的提及。 到目前为止,我的代码如下: Dim a As String = TextBox1.Text + " " Dim b As Char() = a.ToCharArray Dim c As String Dim l As Integer = TextBox1.Text.Length Dim temp As Integer = 0 Dim nex A
Dim a As String = TextBox1.Text + " "
Dim b As Char() = a.ToCharArray
Dim c As String
Dim l As Integer = TextBox1.Text.Length
Dim temp As Integer = 0
Dim nex As Integer = a.IndexOf(" ")
For i = 0 To l - 1
If b(i) = "@" Then
temp = 1
ElseIf temp = 1 Then
temp = 2
End If
If temp = 2 Then
c = a.Substring(i, nex).Trim() 'nex needs be replaced with next space on 2nd or nth loop
MsgBox(c)
temp = 0
nex = a.IndexOf(" ") + nex
End If
Next
现在,如果输入的文本是-@one@twwo@three,这将非常有效。(如果
下一个字符串的长度更大。)但在其他地方不起作用
另外,两次@提及之间可能会有内容,所以我不愿意更改b(I)
我相信有一种更有效的方法可以做到这一点。
谢谢 这是用于
regex
的作业。模式@\w+
应该很好
For Each m As Match In Regex.Matches("@testing this is a @test", "@\w+")
Console.WriteLine(m.Value)
Next
将打印出@testing
和@test
此模式基本上意味着“查找以“@”开头,后跟一个或多个“单词字符”的所有内容。”
Regex是搜索字符串的一个非常强大的工具,您可以在上面阅读更多有关它的信息。我不知道twitter用户名中允许使用哪些字符,因此它可能会遗漏一些内容,甚至匹配一些不应该的内容,但它应该非常准确。如果你看到它发现了一些不应该的东西,或者遗漏了一些东西,请告诉我这些是什么,我会为你调整模式。例如,当查看“@first.last”时,它只返回“@first”。当然。如果有什么事情不符合我的意愿,我会检查案例并发表评论。:)再次感谢。这使工作容易多了D