首页 > 解决方案 > 从 Python 或 Excel 中的字符串中提取多个数值

问题描述

我有一个这样的字符串:

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。

标签: excelvbainformation-extraction

解决方案


此函数将返回字符串中日期之后的数值数组。

  • 它假定前面的数据始终采用 的格式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

在此处输入图像描述


推荐阅读