从带有附加条件的字符串中提取8位数字

lev*_*ski 5 regex string vba extract extraction

我需要从具有多个条件的字符串中提取数字。

  1. 它必须以1-9开头,而不是0,并且它将有8位数字。像23242526或65478932
  2. 之前将有一个空格或一个文本变量。像MMX:23242526或bgr65478932
  3. 它可能在极少数情况下出现:23,242,526
  4. 它以emty空格或文本变量结尾。

以下是几个示例:

  • RE:Markitwire:120432889:Mx:24,693,059我需要得到24693059

  • 自动回复:Auftrag zurÜbertragungIRD Ref-Nr。MMX_23497152需要获取23497152

  • 固件:CGMSE 2019-2X A1AN XS2022418672合同24663537需要获得24663537
  • RE:BBVA-MAD MMX_24644644 + MMX_24644645需要获得24644644、24644645

现在,我正在使用regexextract函数(在此网站上找到),该函数提取以2开头的8位数字。但是,它也将从表达式TGF00023242526提取数字,这是不正确的。而且,我不知道如何在代码中添加其他条件。

=RegexExtract(A11, ""(2\d{7})\b"", ", ")
Run Code Online (Sandbox Code Playgroud)

先感谢您。

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
Run Code Online (Sandbox Code Playgroud)

Wik*_*żew 4

您可以在您拥有的模式之前使用非捕获组创建自定义边界:

(?:[\D0]|^)(2\d{7})\b
^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

(?:[\D0]|^)部分与字符串 ( ) 的非数字 ( \D) 或0( |) 开头匹配^