Get only numbers from string

前端 未结 8 540
耶瑟儿~
耶瑟儿~ 2021-01-01 15:37

i want to get only numbers from string.

Lest say that this is my string :

324ghgj123

i want to get:

324123
相关标签:
8条回答
  • 2021-01-01 15:57

    You can actually combine some of these individual answers to create a single line solution that will either return an integer with the value 0, or an integer that is the concatenation of all of the numbers in the string. Not sure how useful that is, however -- this began as a method to create a string of numbers only....

        Dim TestMe = CInt(Val(New Text.StringBuilder((From ch In "123abc123".ToCharArray Where IsNumeric(ch)).ToArray).ToString))
    
    0 讨论(0)
  • 2021-01-01 15:57
    str="something1234text456"   
    
    Set RegEx = CreateObject("vbscript.regexp")
    RegEx.Pattern = "[^\d+]"
    RegEx.IgnoreCase = True
    RegEx.Global = True
    numbers=RegEx.Replace(str, "")(0)
    msgbox numbers
    
    0 讨论(0)
  • 2021-01-01 16:00
    resultString = Regex.Match(subjectString, @"\d+").Value;
    

    will give you that number as a string. Int32.Parse(resultString) will then give you the number.

    0 讨论(0)
  • 2021-01-01 16:02

    try this:

    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
    

    or:

    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
    
    0 讨论(0)
  • 2021-01-01 16:03

    Or you can use the fact that a String is an Array of 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
    
    0 讨论(0)
  • 2021-01-01 16:10

    you can use Regex for this

    Imports System.Text.RegularExpressions
    

    then on some part of your code

    Dim x As String = "123a123&*^*&^*&^*&^   a sdsdfsdf"
    MsgBox(Integer.Parse(Regex.Replace(x, "[^\d]", "")))
    
    0 讨论(0)
提交回复
热议问题