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

强颜欢笑 提交于 2019-12-30 11:12:12

问题


I have an HTMLElementCollection that I'm going through using a For Each Loop to see if the InnerHTML contains certain words. If they do contain any of those keywords it gets saved into a file.

Everything works fine but I was wondering if there is a way to simplify. Here's a sample

For Each Helement As HtmlElement In elements

     If Helement.InnerHtml.Contains("keyword1") Or Helement.InnerHtml.Contains("keyword2") Or Helement.InnerHtml.Contains("keyword3") Or Helement.InnerHtml.Contains("keyword4") Or Helement.InnerHtml.Contains("keyword5") = True Then
         ' THE CODE TO COPY TO FILE
     End If

Next Helement

Does anything exist that would work like:

If Helement.InnerHtml.Contains("keyword1", "keyword2", "keyword3", "keyword4", "keyword5")

The way I'm doing it now just seems wasteful, and I'm pretty OCD about it.


回答1:


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 :)




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/2212719/vb-net-adding-more-than-1-string-to-contains

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!