【问题标题】:Detect if Specific words found .Net检测是否找到特定单词.Net
【发布时间】:2018-11-12 13:03:56
【问题描述】:

您好,我尝试查找代表数字的特定单词

例如:
- 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

【问题讨论】:

  • 我想有点儿得到你想要的,但只是为了确定:你想写在一个盒子里,点击一个按钮,然后在第一个盒子里找到的所有数字都被重新写在第二个盒子?
  • 不要使用Contain(),使用Equals(),也许添加StringComparison.CurrentCultureIgnoreCaseRegex.Matches 可能会更好,如果您还想知道有多少 找到 符合条件的单词 以及它们在文本中的位置。
  • 首先,直接输出。它永远不会显示找到的内容(string s 中的内容),因为它会被文本 Founded 覆盖。你会看到它会输出一些与你想象的不同的东西。

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


【解决方案1】:

我认为这可能会更好:

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

【讨论】:

  • 你太棒了,这是我想要的特别感谢,来自世界上最好的线程“StackoverFlow”的 Grate 解决方案,帮助了很多人。
猜你喜欢
  • 2017-11-10
  • 2013-08-12
  • 2016-08-19
  • 2011-10-28
  • 2013-08-19
  • 2019-02-11
  • 1970-01-01
  • 2013-12-23
相关资源
最近更新 更多