检测是否找到特定词

时间:2018-11-12 13:03:57

标签: .net regex vb.net visual-studio-2012

你好,我尝试找到代表数字的特定单词

例如:
 -RichTextBox中的数字“一”

我的代码:

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim str As String = RichTextBox1.Text
    Dim strarr() As String
    strarr = str.Split(" "c)
    For Each s As String In strarr

        Dim words() As String = s.ToLower.Split({" "c}, StringSplitOptions.RemoveEmptyEntries)
        If words.Count(Function(w) RichTextBox2.Text.Contains(w)) > 0 Then

            Label1.Text = s
            Label1.Text = "Founded"
        Else
            Label1.Text = "not founded, if we find it, we will type it , in label1"
        End If
    Next

End Sub

RichTextBox2 =我的单词(1-5)数字列表。
RichTextBox1 =我关注的重点。

问题是当我输入RichTextBox1.text
hello i want type numbers, on
它将“ on”检测为(一个)。这不是我的目的。

explaining By picture

1 个答案:

答案 0 :(得分:0)

我认为这可能会更好:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    ' first remove any previous Label1 text
    Label1.Text = ""

    ' cleanup the RichTextBox2 text by replacing any whitespace or non-word character by a single space character
    ' make it all lowercase and trim off the spaces left and right
    Dim keyText As String = (Regex.Replace(RichTextBox2.Text, "[\s\W]+", " ")).ToLower().Trim()
    ' next, split it into an array of keywords
    Dim keyWords As String() = keyText.Split(" "c)

    ' get the user input and prepare it for splitting into words like we did with the RichTextBox2 text
    Dim input As String = (Regex.Replace(RichTextBox1.Text, "[\s\W]+", " ")).ToLower().Trim()

    ' split the cleaned-up input string into words and check if they can be found in the keyWords array
    ' if we do find them, we want only list them once so collect them first in a List
    Dim wordsFound As New List(Of String)
    For Each word As String In input.Split(" "c)
        If keyWords.Contains(word.ToLower()) Then
            If Not (wordsFound.Contains(word)) Then
                wordsFound.Add(word)
            End If
        End If
    Next
    ' finally, add the result to the label
    Label1.Text = String.Join(Environment.NewLine, wordsFound)
End Sub

demo