正则表达式 - 获取/之间的所有字符串之间的字符串?

时间:2011-10-04 17:23:21

标签: .net regex vb.net

我似乎只能在这个主题上找到PHP的帮助,所以我开了一个新问题!

我编写了一个函数来获取另外两个字符串之间的字符串,但目前它仍然返回字符串的第一部分,只是在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

1 个答案:

答案 0 :(得分: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