excel - 从 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。
解决方案
此函数将返回字符串中日期之后的数值数组。
- 它假定前面的数据始终采用 的格式
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
推荐阅读
- python - 在 python stanfordnlp 中使用斯坦福依赖项(而不是通用依赖项)
- mysql - MySQL LEFT JOIN 与 ON 子句中的一列
- javascript - 当 parent 和 child 是函数组件时 React refs
- html - 如何在列中垂直居中内容?
- coreml - CoreML:无法执行矩阵乘法
- excel - 统计所有在“特定月份”注册但在“其他月份”转换的人
- tfs - 将测试用例导出到电子邮件看到错误“:”字符,十六进制值 0x3A,不能包含在名称中
- microsoft-graph-api - Microsoft graph API - 订阅任何日历时出现未经授权的错误
- intellij-idea - 如何在 intellij 文件观察器中调试 sass。找不到输出窗口
- sql - 删除保留最新记录的重复记录