在Python或Excel中从字符串中提取多个数值

时间:2019-06-03 16:56:13

标签: excel vba information-extraction

我有一个像这样的字符串:

Adjustment-05/15/2019-2,000-Random text-Adjustment-05/16/2019-203.57

我只需要提取2000并将其放在一栏中,将203.57放在另一栏中。这些值可能会超过两个。

不胜感激!

我尝试在Excel中删除有效的日期和文本,但随后我仍然有2个不知道如何分隔的值。我尝试了以下两个功能,但效果很好,但仍然无法提取第二个或第三个数值。

Public Function ExtractNumber(inValue As String) As Double
    With New RegExp
        .Pattern = "(\d{1,3},?)+(\.\d{2})?"
        .Global = True
        If .Test(inValue) Then
            ExtractNumber = CDbl(.Execute(inValue)(0))
        End If
    End With
End Function

Function RemoveDates(MyRange As Range) As String
    Dim sRaw As String
    Dim sPattern As String
    Dim regEx As New RegExp

    sRaw = MyRange.Value

    sPattern = "[0-9]{1,2}[-.\\/][0-9]{1,2}[-.\\/][0-9]{4}"

    With regEx
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .Pattern = sPattern
    End With

    If regEx.Test(sRaw) Then
        RemoveDates = regEx.Replace(sRaw, "")
    Else
        RemoveDates = "Not matched"
    End If
    Set regEx = Nothing
End Function

我要查找的结果是一列为2000,另一列为203.57。

1 个答案:

答案 0 :(得分:1)

此函数将返回一个数字值数组,该字符串跟在字符串中的日期之后。

  • 如您在单个示例中所示,它假定前面的数据始终为nn/nn/nnnn-格式。
  • 它还假设将没有nn/nn/nnnn-的另一个实例而不是日期。
  • 该日期之后的值位于捕获组中。
  • 它将返回字符串中存在的所有这些值。

您可以输入n列作为数组,也可以使用INDEX函数分别返回每个值:

Option Explicit
Function ExtractNums(S As String) As Double()
    Dim RE As Object, MC As Object, M As Object
    Dim D() As Double, I As Long
Set RE = CreateObject("vbscript.regexp")
With RE
    .Pattern = "\d{2}/\d{2}/\d{4}-([\d,.]+)"
    .Global = True
    If .test(S) = True Then
        Set MC = .Execute(S)
        ReDim D(1 To MC.Count)
        I = 0

        For Each M In MC
            I = I + 1
            D(I) = M.submatches(0)
        Next M
    End If
End With
ExtractNums = D

End Function

enter image description here