【问题标题】:Extract an 8 digits number from a string with additional conditions从带有附加条件的字符串中提取一个 8 位数字
【发布时间】:2020-03-11 18:51:44
【问题描述】:

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

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

这里有几个例子:

  • 来自 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

【问题讨论】:

标签: regex vba string extract extraction


【解决方案1】:

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

(?:[\D0]|^)(2\d{7})\b
^^^^^^^^^^^

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

【讨论】:

  • 它似乎工作。谢谢!是否也可以调整从 1 到 9 的所有数字的搜索?因为如果我使用 \d{8}) 它不会排除 0。而且,3-4 位数字会增加。 =)
  • 你可以试试[1-9]{7} 而不是\d{7}
  • @levanski 你可能想要[1-9]\d{7},或者查看SJR 的评论。
【解决方案2】:

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

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

Regex demo

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-29
    • 2013-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多