VB.NET - Adding more than 1 string to .contains

梦想的初衷 提交于 2019-12-01 10:55:18

You could write an Extension Method to string that provides a multi-input option, such as:

 Public Module StringExtensionMethods
     Private Sub New()
     End Sub
     <System.Runtime.CompilerServices.Extension> _
     Public Function Contains(ByVal str As String, ByVal ParamArray values As String()) As Boolean
         For Each value In values
             If str.Contains(value) Then
                 Return True
             End If
         Next
         Return False
     End Function
 End Module

You could then call that instead, as in your second example :)

1) One approach would be to match the InnerHtml string against a regular expression containing the keywords as a list of alternatives:

Imports System.Text.RegularExpressions

Dim keywords As New Regex("keyword1|keyword2|keyword3")

...

If keywords.IsMatch(HElement.InnerHtml) Then ...

This should work well if you know all your keywords beforehand.

2) An alternative approach would be to build a list of your keywords and then compare the InnerHtml string against each of the list's elements:

Dim keywords = {"keyword1", "keyword2", "keyword3"}

...

For Each keyword As String In keywords
    If HElement.InnerHtml.Contains(keyword) Then ...
Next

Edit: The extension method suggested by Rob would result in more elegant code than the above approach #2, IMO.

Here's another extension method that cleans up the logic a little with LINQ:

<Extension()>
Public Function MultiContains(str As String, ParamArray values() As String) As Boolean
    Return values.Any(Function(val) str.Contains(val))
End Function
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!