2011-10-04 166 views
0

我似乎只能找到這個問題上的PHP的幫助,所以我打開一個新的問題!正則表達式 - 獲取所有字符串之間的字符串Betwen?

我寫了一個函數來獲取其他2串之間,但目前它仍是返回字符串的第一部分,只是在EndSearch值後消除任何一個字符串:

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 

演示使用方法:

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) 

返回:你好找到我

此外,在PHP我有以下功能:

function get_all_strings_between($string, $start, $end){ 
preg_match_all("/$start(.*)$end/U", $string, $match); 
return $match[1]; 
} 

在VB.NET中是否有類似preg_match_all函數?

示例功能(非功能性,由於返回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) 
     If 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 
+0

爲什麼你需要所有的正則表達式?獲取'StartSearch'的索引,找到'EndSearch'並使用'Substring'來提取匹配。 – NullUserException

+0

我正在使用正則表達式,所以得到一個函數,我也可以用於函數之間的get_all_strings,因爲我無法想到在搜索索引時執行此操作的邏輯方法。 – Chris

回答

2

我不明白,爲什麼你正在使用前瞻:

Dim rx As New Regex("(?=" & StartSearch & ").+(?=" & EndSearch & ")") 

如果StartSearch = helloEndSearch = world,這產生:

(?=hello).+(?=world) 

其中,與字符串匹配,找到並回報到底是什麼。建立像這樣:

Dim rx As New Regex(StartSearch & "(.+?)" & EndSearch) 
Dim m As Match = rx.Match(Haystack) 
If m.Success Then 
    Return m.Groups(1).ToString() 

' etc 
+0

感謝您的回覆,是否有可能返回一個m.Groups數組?例如。 (CODE已被增加至原始問題) – Chris

+0

我猜你希望每個單詞(空格分隔)在一個組?在這種情況下,只需在m.Groups(1)上調用.split(「」) –

相關問題