【问题标题】:Find changing piece of string from a whole text从整个文本中查找更改的字符串
【发布时间】:2016-03-22 18:51:23
【问题描述】:

我需要从整个文本中找到一段字符串。我知道这段文字的开头是什么,我知道它可能以什么结尾。为了在这里举个例子,我将向您展示一个与我正在搜索的字符串相似的字符串。

aaot:1980

  1. (Aaot:) 无论如何,那部分总是留在那里。
  2. (198) 这三个(可以有更多/更少的数字)总是在变化。
  3. (0, 结束数字) 这部分确实发生了变化,但始终是 1, 2, 3, 4, 5, 6, 7, 8 9, 0。最后一位数字之前的数字也是如此。

我的理论是让程序检查第一部分之后的数字,它永远不会改变并搜索最后一个数字,然后找到它们之间的数字。我不确定这是否可能,但这是我的理论。

我也可以让程序循环遍历数字并等待它找到匹配的数字。只需像这样尝试 aaoa:1,文本不包含 aaoa:1,尝试 aaoa:2,它就会匹配。然后以同样的方式尝试其他数字。不过这种方式要慢得多。

注意!一个文本中很可能有多个这样的字符串。我需要得到整个字符串,而不仅仅是数字。

【问题讨论】:

  • aaoa: 也有可能还是它是一个错字?我可以将其总结为返回冒号后面的数字吗?

标签: .net vb.net string parsing substring


【解决方案1】:

只需使用 SubString 并根据字符串的长度调整长度即可:

Dim s As String = "Aaot:1980"
Dim i As Integer
If Integer.TryParse(s.SubString(5, s.Length - 6), i) Then
    Msgbox("The number in the string is " & i.ToString)
Else
    MsgBox("Number could not be parsed")
End If

【讨论】:

  • 非常感谢您提供的功能。但是还是有问题。如果字符串是这样的“asdgf gfdgfd aaot:1980”编辑:或者这个“jjas jfgfd aaot:1927 lkoam aaot:1954”,我如何找到整数
  • "Aaot:无论如何,那部分总是留在那里。" - 所以不是吗?
  • 确实如此,只是在文本中。这部分永远不会改变。
【解决方案2】:

如果我们要查找冒号后面的数字,那么这将返回这些数字的列表。

Private Function GetDoubles(Text As String) As List(Of Double)
    Dim parts() As String = Split(Text, ":")
    Dim results As New List(Of Double)
    For i As Integer = 1 To parts.Count Step 2 'Odd numbered elements will start with numbers
        results.Add(Val(parts(i))) 'Val function processes only the characters that can be part of a number and ignores the rest.
    Next
    Return results
End Function

如果数字始终是整数,则此代码将起作用:

Private Function GetIntegers(Text As String) As List(Of Integer)
    Dim parts() As String = Split(Text, ":")
    Dim results As New List(Of Integer)
    For i As Integer = 1 To parts.Count Step 2 'Odd numbered elements will start with numbers
        results.Add(CInt(Val(parts(i)))) 'Val function processes only the characters that can be part of a number and ignores the rest.
    Next
    Return results
End Function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-23
    • 1970-01-01
    • 2013-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-31
    • 1970-01-01
    相关资源
    最近更新 更多