You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在VB.net中解析拆分动态字符串以提取数字

在VB.NET中提取字符串中的所有数字(整数/小数)

要从任意格式的字符串里提取所有数字(包括整数和带小数点的小数),用正则表达式是最高效的方式——你提到的Regex.Match只能获取第一个匹配项,要拿到所有结果得用Regex.Matches。

核心代码实现

先导入正则表达式的命名空间:

Imports System.Text.RegularExpressions

然后写一个通用的提取函数:

Public Function ExtractAllNumbers(inputString As String) As List(Of String)
    Dim numbersList As New List(Of String)()
    ' 正则模式:匹配整数、小数,支持可选负号(不需要负号可以去掉前半段)
    Dim regexPattern As String = "-\d+(\.\d+)?|\d+(\.\d+)?"
    Dim allMatches As MatchCollection = Regex.Matches(inputString, regexPattern)
    
    For Each singleMatch As Match In allMatches
        If singleMatch.Success Then
            numbersList.Add(singleMatch.Value)
        End If
    Next
    
    Return numbersList
End Function

测试你的示例

示例1

Dim input1 As String = "25% initial deposit, 60% equipment deposit, 15% due upon completion"
Dim result1 = ExtractAllNumbers(input1)
' 输出:25、60、15

示例2

Dim input2 As String = "Payment Schedule: 0.75, 0.25"
Dim result2 = ExtractAllNumbers(input2)
' 输出:0.75、0.25

示例3

Dim input3 As String = "12.5% due upon signing contract, 25-25-25 monthly deposits, 12.5% due upon completion"
Dim result3 = ExtractAllNumbers(input3)
' 输出:12.5、25、25、25、12.5

正则模式说明

  • \d+:匹配1个或多个数字(对应整数部分)
  • (\.\d+)?:可选的小数部分,\.匹配小数点,\d+匹配小数点后的数字,?表示这部分可以不存在
  • -\d+(\.\d+)?:如果需要提取负数,保留这段;不需要的话直接用\d+(\.\d+)?即可

进阶:转换成数值类型

如果需要把提取到的字符串转成Double类型(方便后续计算),可以修改函数:

Public Function ExtractAllNumbersAsDoubles(inputString As String) As List(Of Double)
    Dim numbersList As New List(Of Double)()
    Dim regexPattern As String = "-\d+(\.\d+)?|\d+(\.\d+)?"
    Dim allMatches As MatchCollection = Regex.Matches(inputString, regexPattern)
    
    For Each singleMatch As Match In allMatches
        Dim num As Double
        If Double.TryParse(singleMatch.Value, num) Then
            numbersList.Add(num)
        End If
    Next
    
    Return numbersList
End Function

内容的提问来源于stack exchange,提问作者SteveKr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 17:57:19