在 Visual Basic (VB) 中,你可以使用不同的方法来提取字符串中的数字。下面土嘎嘎小编分享几种常见的方法:
1. 使用 IsNumeric 和循环检查每个字符:
〓〓vb代码如下:〓〓
Dim str As String = "abc123xyz"
Dim numbers As String = ""
For Each ch As Char In str
If IsNumeric(ch) Then
numbers += ch
End If
Next
Console.WriteLine(numbers) ' 输出:123
2. 使用正则表达式提取数字:
〓〓vb代码如下:〓〓
Imports System.Text.RegularExpressions
Dim str As String = "abc123xyz"
Dim regex As New Regex("\d+")
Dim matches As MatchCollection = regex.Matches(str)
Dim numbers As String = ""
For Each match As Match In matches
numbers += match.Value
Next
Console.WriteLine(numbers) ' 输出:123
3. 使用 LINQ 查询提取数字:
〓〓vb代码如下:〓〓
Dim str As String = "abc123xyz"
Dim numbers As String = New String(str.Where(Function(c) Char.IsDigit(c)).ToArray())
Console.WriteLine(numbers) ' 输出:123
这些方法都可以根据你的需求从字符串中提取数字。注意,以上方法假定只提取连续的数字字符。如果需要提取非连续的数字字符或者处理更复杂的数字形式(如带小数点、负号等),可能需要使用更为复杂的逻辑或正则表达式模式来实现。