Friday, May 8, 2020

[VB][Example] Get String between 2 strings

Function
Private Function GetInnerContent(ByVal source As String, ByVal openStr As String, ByVal closeStr As String) As String
  Dim regex = New Regex(openStr+"(.*?)"+closeStr)
  Dim str As String = ""
 
  Try
    Dim matches = regex.Matches(source)
    For Each m As match In mateches
      str = m.Value
    Next
  Catch e As NullReferenceException
    Debug.Write("Cannot get inner text of "+openStr+" and "+closeStr)
  End
  If str.Length > 0 Then
    GetInnerContent = str.Replace(openStr, String.Empty) Replace(closeStr, String.Empty)
  Else
    GetInnerContent = source
  End if
End Function
Usage
Dim title As String = getInnerContent(source,"<title>","</title>")
Dim content As String = getInnerContent(source,"<body>","</body>")

No comments :

Post a Comment