如何从' - '中提取值VB.Net

时间:2015-08-08 05:36:04

标签: asp.net regex vb.net string split

我在VB.Net中有一个函数,它有两个参数(dosage& no_days)。 '剂量'具有1-2-1格式的值 我需要从字符串中获取整数值:例如,如果字符串是1-1-2,我需要将值设为112。这三个数字的总和需要乘以no_days并返回结果 我需要知道如何使用正则表达式"-"或任何其他逻辑来拆分字符串。

Public Function calculateNoOfPeices(ByVal dosage As String, ByVal days As Integer) As String
    Dim noOfPiece As Double = 0.0
    If txt_dosage.Text.Length > 4 Then

        ' need logic to extract the values from the dosage
        'and need to multiply with no_days

    Else
        'lbl_notif.Visible = False
        noOfPiece = "-1"
    End If

    Return noOfPiece.ToString

End Function

请帮忙。

1 个答案:

答案 0 :(得分:1)

使用String.Split

    Dim dosage As String = "1-2-1"
    Dim IntValues() As String = dosage.Split("-")
    Dim fValue As Double = Val(IntValues(0))
    Dim sValue As Double = Val(IntValues(1))
    Dim tValue As Double = Val(IntValues(2))

使用Regx

    Dim pattern As String = "-"
    Dim substrings() As String = Regex.Split(dosage, pattern)
    Dim fValueR As Double = Val(substrings(0))
    Dim sValueR As Double = Val(substrings(1))
    Dim tValueR As Double = Val(substrings(2))

或者你可以使用以下来获取总和:

 Dim overAllSum = dosage.Split("-").ToList().Where(Function(x) IsNumeric(x)).Sum(Function(y) Val(y))