2013-02-26 179 views
1

我想檢查一個字符串是否與數組中的某個字匹配,而不僅僅是匹配字符。 contains方法只檢查匹配字符而不是整個單詞。這裏是我的代碼:vb.net如何檢查一個字符串是否有某個字

Dim builder As New StringBuilder() 
    Dim reader As New StringReader(txtOCR.Text) 
    Dim titles() As String = {"the", "a", "an", "of"} 
    Dim regex As New Regex(String.Join("|", titles), RegexOptions.IgnoreCase) 

    While True 
     Dim line As String = reader.ReadLine() 
     If line Is Nothing Then Exit While 
     Dim WordCount = New Regex("\w+").Matches(line).Count 

     If WordCount = 1 And Not line.ToLower().Contains("by") Then 
      builder.AppendLine(line) 
     ElseIf regex.IsMatch(line) Then 
      builder.AppendLine(line) 
     End If 

    End While 
    txtTitle.Text = builder.ToString() 

回答

3

您可以使用單詞邊界\b包圍的單個單詞:

New Regex("\b" & String.Join("\b|\b", titles) & "\b") 
+0

非常感謝你! :) – user2107624 2013-02-27 00:05:19

+0

@ user2107624不要忘記upvote並接受幫助你的答案 – 2013-02-27 00:06:18

相關問題