只获取字符串中的数字

Nh1*_*123 17 vb.net winforms

我想从字符串中只获取数字.

不要说这是我的字符串:

324ghgj123

我想得到:

324123
Run Code Online (Sandbox Code Playgroud)

我试过的:

MsgBox(Integer.Parse("324ghgj123"))
Run Code Online (Sandbox Code Playgroud)

Joh*_*Woo 28

你可以用Regex

Imports System.Text.RegularExpressions
Run Code Online (Sandbox Code Playgroud)

然后在你的代码的某些部分

Dim x As String = "123a123&*^*&^*&^*&^   a sdsdfsdf"
MsgBox(Integer.Parse(Regex.Replace(x, "[^\d]", "")))
Run Code Online (Sandbox Code Playgroud)

  • 所以你的正则表达式读取:用空字符串替换每个非数字字符.优雅. (2认同)

fam*_*amf 20

试试这个:

Dim mytext As String = "123a123"
Dim myChars() As Char = mytext.ToCharArray()
For Each ch As Char In myChars
     If Char.IsDigit(ch) Then
          MessageBox.Show(ch)
     End If
Next
Run Code Online (Sandbox Code Playgroud)

要么:

Private Shared Function Num(ByVal value As String) As Integer
    Dim returnVal As String = String.Empty
    Dim collection As MatchCollection = Regex.Matches(value, "\d+")
    For Each m As Match In collection
        returnVal += m.ToString()
    Next
    Return Convert.ToInt32(returnVal)
End Function
Run Code Online (Sandbox Code Playgroud)


Mar*_*all 5

或者您可以使用String是Chars数组的事实.

Public Function getNumeric(value As String) As String
    Dim output As StringBuilder = New StringBuilder
    For i = 0 To value.Length - 1
        If IsNumeric(value(i)) Then
            output.Append(value(i))
        End If
    Next
    Return output.ToString()
End Function
Run Code Online (Sandbox Code Playgroud)