例如,150safdsdfsdf123456应该产生150如何从字符串前的数字中获取值?
如果文本是150,那么很容易。只需使用val。不过,我也希望能够阅读150sdfsdfsdafsadf,不管怎样。
我该怎么办?
例如,150safdsdfsdf123456应该产生150如何从字符串前的数字中获取值?
如果文本是150,那么很容易。只需使用val。不过,我也希望能够阅读150sdfsdfsdafsadf,不管怎样。
我该怎么办?
使用正则表达式(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
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]。“ –
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
提取数。如果你只是想在开始并没有在中间或结尾的号码,使用这个
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(它接受小数!)
当我使用Val()但我可能就是这样......我是偏执狂...... –
@JasonBayldon完全。它让我想起了我的VB6日子。但是,根据OP想要做什么,Val看起来工作得很好。这个问题有些含糊。 – djv
经常val的作品?为什么没有人告诉我这些? –
要在字符串的开头匹配一个号码,就可以使用正则表达式:
Imports System.Text.RegularExpressions
Dim input As String = "150safdsdfsdf123456"
Dim re As New Regex("^\d+")
Dim output As String = re.Match(input).Value
注意到^
符号,它意味着字符串的开始。所以这个,例如,a150safdsdfsdf123456
将不会被匹配。
你的字符串可以包含多个数值吗?例如150fjadfadf24ffaf1234 – HKImpact
如果是这样,我只想要第一个。 –
@JimThio我更新了您的示例以反映您的最新评论。 – djv