【发布时间】:2011-10-04 17:23:21
【问题描述】:
我似乎只能在这个主题上找到 PHP 的帮助,所以我提出了一个新问题!
我已经编写了一个函数来获取其他 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
【问题讨论】:
-
为什么需要正则表达式?获取
StartSearch的索引,找到EndSearch并使用Substring提取匹配。 -
我使用 Regex 来获取一个函数,该函数也可以用于函数之间的 get_all_strings,因为在搜索索引时我想不出一种合乎逻辑的方法。