2011-10-04 165 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(“”) –

相关问题