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.
Eve开发者_运维百科rything 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) 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.
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 :)
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
精彩评论