2012-11-13 70 views
13

我只想從字符串中獲取數字。只獲取字符串中的數字

免得說,這是我的字符串:

324ghgj123

我想:

324123 

我曾嘗試:

MsgBox(Integer.Parse("324ghgj123")) 

回答

19

試試這個:

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 

或:

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

謝謝。作品。 – Nh123

+0

沒問題。 :-) – famf

22

您可以使用Regex這個

Imports System.Text.RegularExpressions 

然後在你的代碼的某些部分

Dim x As String = "123a123&*^*&^*&^*&^ a sdsdfsdf" 
MsgBox(Integer.Parse(Regex.Replace(x, "[^\d]", ""))) 
+0

這適用於。謝謝。 – Nh123

+2

所以你的正則表達式是:用空字符串替換每個非數字字符。優雅。 – Jonathan

4

或者你可以使用一個事實,即一個String是一個字符數組。

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 
2
resultString = Regex.Match(subjectString, @"\d+").Value; 

會給你這個數字作爲一個字符串。然後Int32.Parse(resultString)會給你這個數字。

+0

這是C#,而不是VB.NET,否則,最短的,謝謝! – monami

0

對於線性搜索方法,您可以使用這種算法,它使用C#,但可以很容易地在vb.net中翻譯,希望它有幫助。

string str = 「123a123」; 

for(int i=0;i<str.length()-1;i++) 
{ 
    if(int.TryParse(str[i], out nval)) 
     continue; 
    else 
     str=str.Rremove(i,i+1); 
} 
0

實際上,你可以結合一些個別的答案創建一個單一的線解決方案,要麼值爲0,或者一個整數的所有字符串中的數字的級聯返回一個整數。然而,不知道這是多麼有用 - 這開始作爲創建一串數字的方法...

Dim TestMe = CInt(Val(New Text.StringBuilder((From ch In "123abc123".ToCharArray Where IsNumeric(ch)).ToArray).ToString)) 
相關問題