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

Extract an 8 digits number from a string with additional conditions

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

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

这里有几个例子:

现在我正在使用 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
^^^^^^^^^^^

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

作为替代方法,也可以匹配 23,242,526 等值中的 8 位数字并以数字 1-9 开头,您可以使用

\b[1-9](?:,?\d){7}\b
  • \b 字边界
  • [1-9]匹配第一个数字1-9
  • (?:,?\d){7} 重复 7 次匹配一个可选的逗号和一个数字
  • \b 字边界

Regex demo

然后你可以用空字符串替换逗号。