2012-11-13 68 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)) 
相关问题