文本拆分问题

时间:2011-06-01 11:42:04

标签: .net vb.net

我有一个程序可以扫描textbox1文本,并显示textbox1中textbox2中长度超过n个字母的所有单词。这是完整的代码:

Private Function filterWords(ByVal minLenght As Short, ByVal input As String) As List(Of String)
        Dim strInput() As String = input.Split(" ")
        Dim strList As New List(Of String)
        strList = strInput.ToList()

        For Each word In strInput
            If word.Length < minLenght Then
                strList.Remove(word)
            End If
        Next
        Return strList
    End Function

    Private Sub textbox1_TextChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles textbox1.TextChanged
        textbox2.Text = ""
        Dim strOut As New List(Of String)

        strOut = filterWords(4, textbox1.Text)

        For Each w In strOut
            textbox2.Text += w & " "
        Next
    End Sub

例如,如果您键入 abcd ,则它不会在textbox2中显示任何内容,但如果您键入 a ,请按Enter键,然后按 b ,它会显示它们。我应该写什么来避免这种情况?

1 个答案:

答案 0 :(得分:2)

这实际上取决于你如何定义一个单词。您当前的实现定义了一个空间捐赠单词的结尾。您只需将空格传递给input.Split即可定义此值。如果您还想定义句点(。)结束单词,请添加它:input.Split(" .")
如果您想在新行上结尾,请添加:input.Split(" ." & Environment.NewLine.ToString())

另一种方法是使用正则表达式,也许是这样:

Private Function filterWords(ByVal minLength As Short, ByVal input As String) _
    As List(Of String)

    Dim strList As New List(Of String)
    Dim wordMatches = Regex.Matches(input, "\w+").Cast(Of Match)
    For Each wordMatch In wordMatches
        If wordMatch.Value.Length >= minLength Then
            strList.Add(wordMatch.Value)
        End If
    Next
    Return strList

End Function