我有一个富文本框填充了一些文本(例如[mplampla],[randomstring],[string] ...)。 richtextbox有很多行。 我试图获得“[”和“]”之间的所有值,但我不能。
到目前为止,这是我的代码:
For Each line In RichTextBox1.Lines
Dim string1 As String = line
Dim finalstring As String = ""
finalstring = string1.Split("[")(1).Split("]")(0)
MsgBox(finalstring)
Next
答案 0 :(得分:2)
我认为你不能通过使用String.Split来获取括号内的所有值。
正则表达式擅长这些,但您也可以使用IndexOf函数查找括号:
Dim words As New List(Of String)
Dim startIndex As Integer = 0
While startIndex > -1
startIndex = rtb.Text.IndexOf("[", startIndex)
If startIndex > -1 Then
Dim endIndex As Integer = rtb.Text.IndexOf("]", startIndex)
If endIndex > -1 Then
words.Add(rtb.Text.Substring(startIndex + 1, endIndex - startIndex - 1))
End If
startIndex = endIndex
End If
End While
MessageBox.Show(String.Join(Environment.NewLine, words.ToArray))
答案 1 :(得分:1)
试试这个
For Each line In RichTextBox1.Lines
Dim string1 As String = line
Dim betastring As String = ""
Dim finalstring As String = ""
betastring = string1.Split("[")(1)
finalstring = betastring .Split("]")(0)
MsgBox(finalstring)
Next
答案 2 :(得分:1)
(?<=\[)(\w|\s)*(?=\])
考虑以下控制台应用:
Dim str = "this is [my] string [with some] [brackets]"
Dim pattern = "(?<=\[)(\w|\s)*(?=\])"
Dim matches = System.Text.RegularExpressions.Regex.Matches(str, pattern)
For Each match In matches
Console.WriteLine(match)
Next
这导致此输出:
my
with some
brackets
此外,您可以使用Regex.Matches(String, String, RegexOptions)
重载来扩展它以匹配多行文字:
RegularExpressions.Regex.Matches(str, pattern, RegexOptions.Multiline)