Regex - Get String Between / Get All Strings Betwen?
I can only seem to find help for PHP on this subject so am opening a new question!
I have written a function to get a string between 2 other strings but at the moment it is still returning the first part of the string and simply removing anything after the EndSearch value:
Public Function GetStringBetween(ByVal Haystack As String, ByVal StartSearch As String, ByVal EndSearch As String) As String
If InStr(Haystack, StartSearch) < 1 Then Return False
Dim rx As New Regex("(?=" & StartSearch & ").+(?=" & EndSearch & ")")
Return (rx.Match(Haystack).Value)
End Function
Demo Usage:
Dim Haystack As String = "hello find me world"
Dim StartSearch As String = "hello"
Dim EndSearch As String = "world"
Dim Content As String = GetStringBetween(Haystack, StartSearch, EndSearch)
MessageBox.Show(Content)
Returns: hello find me
Also, in PHP I have the following function:
function get_all_strings_between($string, $start, $end){
preg_match_all( "/$start(.*)$end/U", $string, $match );
return $match[1];
}
Is there a similar function in VB.NET for preg_match_all?
Example Function (Non-Functional Due To Returning m.Groups):
Public Function GetStringBetween(ByVal Haystack As String, ByVal StartSearch As String, ByVal EndSearch As String, Optional ByVal Multiple As Boolean = False) As String
Dim rx As New Regex(StartSearch & "(.+?)" & EndSearch)
Dim m As Match = rx.Match(Haystack)
I开发者_开发知识库f m.Success Then
If Multiple = True Then
Return m.Groups
Else
Return m.Groups(1).ToString()
End If
Else
Return False
End If
End Function
I don't understand why you are using lookahead:
Dim rx As New Regex("(?=" & StartSearch & ").+(?=" & EndSearch & ")")
If StartSearch = hello
and EndSearch = world
, this generates:
(?=hello).+(?=world)
Which, matched against the string, finds and returns exactly what it's supposed to. Build something like:
Dim rx As New Regex(StartSearch & "(.+?)" & EndSearch)
Dim m As Match = rx.Match(Haystack)
If m.Success Then
Return m.Groups(1).ToString()
' etc
精彩评论