在我的窗口应用程序中,我想从一个句子中找到确切的单词。这两个字段分别是文本框(单词)和richtextbox(句子)。
我使用了Str(i).contains(word)和For Each match As Regex.Matches(str(i),word)。
但是这两个词并没有得到确切的词。例如, 字:吃 句子:parfaite ment aux exigences cre * ate *évolutivesdumarchédaujourd hui
在上面它取得了创造中的赌注。但我需要集中注意力而不是合并。
答案 0 :(得分:4)
在Regex.Matches中,您需要使用\ b字边界字符。我刚刚在C#中编写了一个示例代码,现在我注意到你的问题是针对VB.NET的,所以我将添加两个代码示例:
<强> C#:强>
//Example 1:
var testString = "parfaite ment aux exigences create évolutives du marché d aujourd hui";
var pattern = "ate";
MatchCollection found = Regex.Matches(testString, @"\b" + pattern + @"\b");
if (found.Count > 0)
{
foreach (Match f in found)
{
Console.WriteLine("'{0}' found at position {1} in given testString.", f.Value, f.Index);
}
}
else Console.WriteLine("No matches in given testString.");
//Example 2:
var testString1 = "parfaite ment aux exigences cre*ate* évolutives du marché d aujourd hui I don't know the language but this: ate and the last one should be found: ate!";
var pattern1 = "ate";
MatchCollection found1 = Regex.Matches(testString1, @"\b" + pattern1 + @"\b");
if (found1.Count > 0)
{
foreach (Match f in found1)
{
Console.WriteLine("'{0}' found at position {1} in given testString1.", f.Value, f.Index);
}
}
else Console.WriteLine("No matches in given testString1.");
Console.ReadLine();
<强> VB.NET:强>
'Example 1:
Dim testString = "parfaite ment aux exigences create évolutives du marché d aujourd hui"
Dim pattern = "ate"
Dim found As MatchCollection = Regex.Matches(testString, "\b" & pattern & "\b")
If found.Count > 0 Then
For Each f In found
Console.WriteLine("'{0}' found at position {1} in given testString.", f.Value, f.Index)
Next
Else
Console.WriteLine("No matches in given testString.")
End If
'Example 2:
Dim testString1 = "parfaite ment aux exigences cre*ate* évolutives du marché d aujourd hui I don't know the language but this: ate and the last one should be found: ate!"
Dim pattern1 = "ate"
Dim found1 As MatchCollection = Regex.Matches(testString1, "\b" & pattern1 & "\b")
If (found1.Count > 0) Then
For Each f As Match In found1
Console.WriteLine("'{0}' found at position {1} in given testString1.", f.Value, f.Index)
Next
Else
Console.WriteLine("No matches in given testString1.")
End If
Console.ReadLine()
答案 1 :(得分:0)
也许这会有所帮助?
Private Sub SearchForWord()
Dim SearchString() As String = Split("ate parfaite ment aux exigences cre*ate* évolutives du marché d aujourd hui", " ")
Dim WordToFind As String = "ate"
Dim count As Integer = 0
Dim NumMatches As Integer = 0
Do Until count = UBound(SearchString)
If UCase$(WordToFind) = UCase$(SearchString(count)) Then
NumMatches = NumMatches + 1
End If
count = count + 1
Loop
Debug.Print(Format(NumMatches))
End Sub