【问题标题】:How to get string between two repeating words?如何在两个重复的单词之间获取字符串?
【发布时间】:2014-03-09 06:05:36
【问题描述】:

我一直致力于从文本文件中获取两个单词之间的字符串,其中这些单词重复了多次。

我的文件中有什么;

 Name: Person1 
 Age: 20

 Name: Person2 
 Age:21

 Name: Person3 
 Age:22

我想要的输出;

Person1 
Person2 
Person3

到目前为止我做了什么;

Public Function StrBtw(ByVal Text_ As String, ByVal Start_ As String, ByVal End_ As String) As String
        Dim V As String = Nothing
        V = Text_.Substring(Text_.IndexOf(Start_) + Start_.Length, Text_.IndexOf(End_) - Text_.IndexOf(Start_) - Start_.Length)
        Return V
    End Function

用法;

        Dim A As String = myFileString

        For i As Integer = 0 To A.Length - 1
            If i = A.IndexOf(W) Then
                TextBox1.Text &= StrBtw(A, "Name: ", "Age: ")
                i = A.IndexOf(W) + "Name: ".Length
            End If
        Next

电流输出;

Person1

如上所述,输出仅显示 Person1 的名称,而我想要所有名称。我认为可能的原因可能是 IndexOf 函数每次都返回到第一个“名称:”。 我尝试使用正则表达式。我发现它非常混乱,结果仍然是一样的。 我已经为此花费了两个小时,因此感谢您提供任何帮助。

【问题讨论】:

    标签: .net regex vb.net string


    【解决方案1】:

    你是对的,问题是IndexOf 只以你使用它的方式检索第一次出现。但是,有一个overload 将搜索的开始索引作为参数。您可以使用此重载并像这样更改代码:

    Public Class Test
        Public Shared Sub Main()
            Dim myFileString = "Name: Person1" & vbNewLine & "Age: 21" & _
                "Name: Person2" & vbNewLine & "Age: 21"
            Dim result As New System.Text.StringBuilder()
            Dim index = myFileString.IndexOf("Name:")
            While (index >= 0)
                Dim indexAge = myFileString.IndexOf("Age:", index)
                If (indexAge >= 0) Then
                    result.AppendLine(myFileString.SubString(index + 5, indexAge - index - 5).Trim())
                End If
                index = myFileString.IndexOf("Name:", indexAge)
            End While
            Console.WriteLine(result)
        End Sub
    End Class
    

    样本在没有附加参数的情况下获取第一个索引;后续的出现都是以“Age:”的索引为起点。您可以运行示例here

    【讨论】:

    • 完美运行。非常感谢:]
    【解决方案2】:

    如果您想使用正则表达式,可以使用该代码:

    Dim matches = Regex.Matches(myFileString, "(?<=Name:\s).*(?=\n)", RegexOptions.Multiline)
    
    For Each Match In matches
        Dim found As String = Match.ToString().Trim()
    Next
    

    【讨论】:

      猜你喜欢
      • 2015-10-09
      • 1970-01-01
      • 2013-06-13
      • 1970-01-01
      • 2017-01-07
      • 2012-06-12
      • 2014-01-31
      • 2021-10-14
      • 2018-09-26
      相关资源
      最近更新 更多