【发布时间】:2020-03-11 18:51:44
【问题描述】:
我需要从具有多个条件的字符串中提取一个数字。
- 它必须以 1-9 开头,而不是从 0 开始,并且它将有 8 位数字。喜欢 23242526 或 65478932
- 前面会有一个空格或一个文本变量。喜欢 MMX:23242526 或 bgr65478932
- 它可能在极少数情况下出现:23,242,526
- 以空空格或文本变量结尾。
这里有几个例子:
来自 RE: Markitwire: 120432889: Mx: 24,693,059 我需要得到 24693059
来自 自动回复:Auftrag zur Übertragung IRD Ref-Nr. MMX_23497152需要得到23497152
- 来自FW: CGMSE 2019-2X A1AN XS2022418672 Contract 24663537需要得到24663537
- 来自RE: BBVA-MAD MMX_24644644 + MMX_24644645需要得到24644644, 24644645
现在我正在使用 regexextract 函数(在这个网站上找到它),它提取任何以 2 开头的 8 位数字。但是它也会从这个表达式 TGF00023242526 中提取一个数字,它是不正确的。此外,我不知道如何在代码中添加附加条件。
=RegexExtract(A11, ""(2\d{7})\b"", ", ")
提前谢谢你。
Function RegexExtract(ByVal text As String, _
ByVal extract_what As String, _
Optional seperator As String = "") As String
Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.Pattern = extract_what
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)
For i = 0 To allMatches.Count - 1
For j = 0 To allMatches.Item(i).SubMatches.Count - 1
result = result & seperator & allMatches.Item(i).SubMatches.Item(j)
Next
Next
If Len(result) <> 0 Then
result = Right(result, Len(result) - Len(seperator))
End If
RegexExtract = result
End Function
【问题讨论】:
-
试试
(?:[\D0]|^)(2\d{7})\b
标签: regex vba string extract extraction