excel - 如何从字符串中准确提取 6 个连续数字
问题描述
问题:如何从字符串中准确提取6 个连续数字
例子:
f657674
576767g
tt454656y
465767yy
x1234567
1234567x
n645856g
s-5656-54654657657-6576-46567785-4354
pof-user-201734545435454
4545665
345678
f546576767g
rtryty
它应该给
657674
576767
454656
465767
(blank value)
(blank value)
645856
(blank value)
(blank value)
(blank value)
345678
(blank value)
(blank value)
我试过的:(A1
是第一个字符串的单元格)
=IFERROR(LOOKUP(10^6;MID(A1;ROW(INDIRECT("1:"&LEN(A1)-5));6)+0);"")
然后我将这个公式拖到其他行,它给出:
657674 (right)
576767 (right)
454656 (right)
465767 (right)
(blank value) (right)
(blank value) (right)
645856 (right)
657457 (wrong)
435454 (wrong)
4545665 (wrong)
345678 (right)
546576767 (wrong)
(blank value) (right)
版本:Excel 2016
解决方案
您可能需要 UDF 而不是内置函数。这应该可行,但可能需要调整。您在 OP 中的示例345678
作为正确的返回返回,但两边都没有字母。因此,我假设您想要:6 个连续的数字,或者 6 个连续的数字,两边都有一个字母。
将此添加到工作簿模块中,您可以调用 like =return_numbers(A1)
。您可能需要也可能不需要将 RegEx 引用添加到 VBEditor。
Function return_numbers(ByVal cel As Range) As String
Dim strPattern As String
Dim regEx As New RegExp
strPattern = "[a-z]\d{6}[a-z]"
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = True
.Pattern = strPattern
End With
Dim matches As Object
Set matches = regEx.Execute(cel)
If Len(cel) = 6 And IsNumeric(cel) Then
return_numbers = cel.Value
Set regEx = Nothing
Exit Function
End If
If matches.Count <> 0 Then
return_numbers = Mid(matches.Item(0), 2, Len(matches.Item(0)) - 2)
ElseIf matches.Count = 0 Then
strPattern = "[a-z]{1}\d{6}$"
regEx.Pattern = strPattern
Set matches = regEx.Execute(cel)
If matches.Count <> 0 Then
return_numbers = Mid(matches.Item(0), 2, Len(matches.Item(0)) - 1)
ElseIf matches.Count = 0 Then
strPattern = "^\d{6}[a-z]{1}"
regEx.Pattern = strPattern
Set matches = regEx.Execute(cel)
If matches.Count <> 0 Then
return_numbers = Mid(matches.Item(0), 1, Len(matches.Item(0)) - 1)
End If
End If
End If
Set regEx = Nothing
End Function
如果您想加快速度,我认为如果您切换If/else
语句,它可能会运行得更快一些,因为它不会总是运行正则表达式,如果它找到 6 个单独的数字
编辑:这相当笨重。我确定有更好的正则表达式模式,所以请告诉我。
推荐阅读
- c# - CosmosDb 字符串搜索
- excel - VBA 使用 InputBox 定义工作表名称并将其存储在变量中
- python - 'function' 对象没有属性 'plot'
- python - 从python中的googlesheet下载表格为csv
- python - 将日期、小时数推断为 datetime64
- android - 缺少或不受支持的字符串?
- docker-volume - 本地文件系统上的 Rancher 卷
- ocaml - 如何编写一个函数来返回 OCaml 中给定集合中具有 k 个元素的所有子集?
- laravel - 显示父子表中的所有数据
- c - 当返回指向复合文字的指针时,gcc 和 clang 不会发出警告