将 stringRaw 从 String1 子串到 String2

Substring a stringRaw from String1 to String2

如果你没有真正理解我真正想要的,让我更好地向你解释:

我有一个:

stringRaw = "<img src=\"http://www.b92.net/news/pics/2015/01/15/111348233854b817af5b4bc991063053_v4 big.jpg\" title=\"\" alt=\"\" />"  

现在我必须做一些从 string1 = "<img src=\""string2 = "\" title=\"\" alt=\"\" />" 的子字符串,并且必须取中间的内容,在这种情况下将是 stringFinal = "http://www.b92.net/news/pics/2015/01/15/111348233854b817af5b4bc991063053_v4 big.jpg"

我无法使用 substring 方法,因为我不知道 string1string2 中可以包含多少个字符,而且 split 方法似乎不起作用Whosebug 上的 THIS 问题应该如此。

edit 出于某种原因,我的 stringRaw 具有此值:vbCrLf & vbTab & vbTab & vbTab & "<img src=""http://www.b92.net/news/pics/2015/02/05/203819435354d39f17d74f0173575440_v4 big.jpg"" title="""" alt="""" />" & vbTab & vbTab
无论如何,我按照其他人的建议做了,但仍然收到 Index is out of range

错误

提前感谢您的回答。

我相信这段代码应该能满足您的需求 'stringFinal'。

// Get the index of 'src="'
Int32 startIndex = stringRaw.IndexOf("src=\"");

// Get the substring starting at 'src="' and ending at the first '"' after 'src="'.
stringRaw.Substring(startIndex, stringRaw.IndexOf("\"", startIndex) - startIndex);

哦,抱歉刚刚注意到 VB 标签。这是 C# 所以 sytnax 可能略有不同,但功能和参数应该仍然相同。

我忘记了 - startIndex 我在想 SubString 第二个参数是一个索引而不是计数。尝试添加该调整。

我在查找相同字符时遇到问题,所以我查找了字符串中的文本,例如 "http" 和 "title="。这是在 VB:

    Dim startIndex As Int32 = stringRaw.IndexOf("http")
    Dim endIndex As Int32 = stringRaw.IndexOf("title=") - 2
    Return stringRaw.Substring(startIndex, endIndex - startIndex)

我使用了 "http" 并且没有包含“://”以防万一您需要在某些时候获得 "https"。我使用 "title=" 而不是 "title" 以防单词标题出现在 link 中。

您也可以使用正则表达式。类似于:

Dim stringRaw as String = vbCrLf & vbTab & vbTab & vbTab & "<img src=""http://www.b92.net/news/pics/2015/02/05/203819435354d39f17d74f0173575440_v4 big.jpg"" title="""" alt="""" />" & vbTab & vbTab
Dim regx as New Regex("src=\""(.*)\""\s+title")
Dim match as Match = regx.Match(stringRaw)

If match.Success
    ' Outputs http://www.b92.net/news/pics/2015/02/05/203819435354d39f17d74f0173575440_v4 big.jpg
    Console.WriteLine(match.Groups(1).Value)
End If
Public Function ExtractSrcAttribute(ByVal element As String) As String
    Dim startToken As String = "src="""
    Dim endToken As String = """"

    Dim startIndex As Integer = element.IndexOf(startToken) + startToken.Length
    Dim endIndex As Integer = element.IndexOf(endToken, startIndex)

    If startIndex > element.Length OrElse endIndex > element.Length OrElse endIndex < startIndex Then
        'error
    End If

    Return element.SubString(startIndex, endIndex)
End Function

正如我在评论中提到的,您可以使用 Regex 轻松完成此操作。这使用 Positive-LookBehindPositive-LookAhead。请看下面的例子。这也经过了试验和测试。

  Dim rgex As New Regex("((?<=src=\"").*)(?=\""\s+title=)")
  Dim mtch As Match = rgex.Match(TextBox1.Text)

  If mtch.Success Then
       MessageBox.Show(mtch.Groups(1).Value)
  End If