2014-07-21 57 views
1

例如,150safdsdfsdf123456应该产生150如何从字符串前的数字中获取值?

如果文本是150,那么很容易。只需使用val。不过,我也希望能够阅读150sdfsdfsdafsadf,不管怎样。

我该怎么办?

+1

你的字符串可以包含多个数值吗?例如150fjadfadf24ffaf1234 – HKImpact

+1

如果是这样,我只想要第一个。 –

+0

@JimThio我更新了您的示例以反映您的最新评论。 – djv

回答

0

使用正则表达式(Regular Expressions)方法从字符串

Dim value1 as String 
Dim temp As Regex = New Regex("\d+") 
Dim match As Match = temp.Match("23333 dsadsa fd") 
If match.Success Then 
    value1 = match.Value 
    Console.WriteLine(value1) 
End If 
+0

OP想要在字符串开头的数字,所以'^ [0-9] +'将是正则表达式使用。或'New Regex(“^ \ d +”,RegexOptions.ECMAScript)'因为从[documentation](http://msdn.microsoft.com/en-us/library/20bw873z%28v=vs.110%29.aspx #DigitCharacter):“\ d匹配任何十进制数字,它等同于\ p {Nd}正则表达式,其中包含标准十进制数字0-9以及其他多个字符集的十进制数字。指定符合ECMAScript的行为,\ d等同于[0-9]。“ –

0
Dim input As String = "150safdsdfsdf" ' input string contains alphanumeric characters. 
Dim output As String = New String((From c As Char In input Select c Where Char.IsDigit(c)).ToArray()) 
' output is a string variable, in the RHS select each character from the input string ('c') 
'and check whether it is a digit or not using IsDigit Function. 
' if yes it is append with the output string 
' else it is neglected. 
'hence we will get only numbers as oru output 
msgbox (output)' output will be 150 
+1

缺少一些逻辑。这将只选择字符。你想'哪里不Char.IsLetter(c)' – djv

+1

@丹Verdolino:是的我得到了我的错误谢谢你,我在我的回答中作出更正 – Suji

+0

你的'IsDigit(c)',优于我的'Not Char.IsLetter(c ),因为它会包含其他符号。谢谢。 – djv

0

提取数。如果你只是想在开始并没有在中间或结尾的号码,使用这个

Dim input As String = "150safdsdfsdf150" 
Dim output As String = New String(input.TakeWhile(Function(c) IsDigit(c)).ToArray()) 

实际上Val()有什么问题?

Dim s = "150.9sdfsdfsdafsadfwhatever654" 
Dim d = Val(s) 

d将是150.9(它接受小数!)

+0

当我使用Val()但我可能就是这样......我是偏执狂...... –

+0

@JasonBayldon完全。它让我想起了我的VB6日子。但是,根据OP想要做什么,Val看起来工作得很好。这个问题有些含糊。 – djv

+0

经常val的作品?为什么没有人告诉我这些? –

0

要在字符串的开头匹配一个号码,就可以使用正则表达式:

Imports System.Text.RegularExpressions 

Dim input As String = "150safdsdfsdf123456" 
Dim re As New Regex("^\d+") 
Dim output As String = re.Match(input).Value 

注意到^符号,它意味着字符串的开始。所以这个,例如,a150safdsdfsdf123456将不会被匹配。

相关问题