如何显示此字符串中的所有数字

时间:2019-05-22 11:44:12

标签: vb.net

我只想显示字符串中的数字。

这是我的输入内容

  

“ aa [12] bb [34] cc [56] dd [78]”

到目前为止,我的代码:

Dim total As String
total = TextBox1.Text
Dim istart As String
Dim iend As String
Dim first As String
Dim second As String
Dim third As String
Dim four As String
Dim icount As String
icount = Len(total)
Do While icount > 0
    istart = total.IndexOf("[")
    iend = total.IndexOf("]") '
    If iend > 0 Then
        first = total.Substring(istart + 1, iend - istart - 1)
        MessageBox.Show(first)

        second = total.Substring(iend + 1, icount - iend - 1)
        MessageBox.Show(second)

        third = second.Substring(istart + 1, iend - istart - 1)
        MessageBox.Show(third)

    Else
        icount = 0
    End If
Loop

我希望输出

  

12
  34
  56
  78

3 个答案:

答案 0 :(得分:3)

Regex是一种简单的方法:

Dim text As String = "aa[12]bb[34]cc[56]dd[78]"

Dim numbers As String() = _
    Regex _
        .Matches(text, "(\d+)") _
        .Cast(Of Match)() _
        .Select(Function(x) x.Value) _
        .ToArray()

或者如果[]很重要:

Dim numbers As String() = _
    Regex _
        .Matches(text, "\[(\d+)]") _
        .Cast(Of Match)() _
        .Select(Function(x) x.Groups(1).Value) _
        .ToArray()
For Each number In numbers
    Console.WriteLine(number)
Next

这就是您得到的:

12 
34 
56 
78 

答案 1 :(得分:1)

我受到this post的启发。

selectItems()

答案 2 :(得分:0)

一种非限制方式。不知道他是否想要字符串或数组中的结果。这样会产生一个字符串。

Dim SourceString As String = "aa[12]bb[34]cc[56]dd[78]"
Dim FinalString As String = String.Empty
Dim Chars() = SourceString.Split("["c)
Dim SecondString = Join(Chars)
Dim NextChars() = SecondString.Split("]"c)
For Each Str As String In NextChars
    FinalString &= System.Text.RegularExpressions.Regex.Replace(Str, "[^\d]", "") & Environment.NewLine
Next