【问题标题】:Regex - Get String Between / Get All Strings Betwen?正则表达式 - 获取字符串之间/获取所有字符串之间?
【发布时间】: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,因为在搜索索引时我想不出一种合乎逻辑的方法。

标签: .net regex vb.net


【解决方案1】:

我不明白你为什么要使用前瞻:

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

【讨论】:

  • 感谢回复,是否可以返回一个 m.Groups 数组?例如。 (代码添加到原始 Q)
  • 我猜你想要一个组中的每个单词(空格分隔)?在这种情况下,只需在 m.Groups(1) 上调用 .split(" ")
猜你喜欢
  • 2019-03-30
  • 2017-07-16
  • 2018-04-30
  • 2014-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多