【问题标题】:Regex return seven digit number match only正则表达式仅返回七位数字匹配
【发布时间】:2017-04-14 21:51:27
【问题描述】:

我一直在尝试构建一个正则表达式来从字符串中提取一个 7 位数字,但很难让模式正确。

示例字符串 - WO1519641 WO1528113TB WO1530212 TB

返回示例 - 1519641, 1528113, 1530212

我在 Excel 中使用的代码是...

Private Sub Extract7Digits()
    Dim regEx As New RegExp
    Dim strPattern As String
    Dim strInput As String
    Dim strReplace As String
    Dim Myrange As Range

    Set Myrange = ActiveSheet.Range("A1:A300")

    For Each c In Myrange
        strPattern = "\D(\d{7})\D"
        'strPattern = "(?:\D)(\d{7})(?:\D)"
        'strPattern = "(\d{7}(\D\d{7}\D))"

        strInput = c.Value

        With regEx
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern
        End With

        If regEx.test(strInput) Then
            Set matches = regEx.Execute(strInput)
            For Each Match In matches
                s = s & " Word: " & Match.Value & " "
            Next
                c.Offset(0, 1) = s
            Else
                s = ""
        End If

    Next
End Sub

我已经尝试了该代码中的所有 3 种模式,但在使用 "\D(\d{7})\D" 时,我最终得到了 O1519641, O1528113T, O1530212 的返回。据我所知,() 没有任何意义,因为我存储匹配项的方式,而我最初认为它们意味着表达式将返回() 中的内容。

我一直在 http://regexr.com/ 上进行测试,但我仍然不确定如何让它允许数字在字符串中,因为 WO1528113TB 只是返回数字。我是否需要对 RegEx 的返回值运行 RegEx 以第二次排除这些字母?

【问题讨论】:

  • 您需要的预期结果是单个字符串还是数组/集合?
  • 我可以使用其中任何一个,但理想情况下我需要从集合中返回最大的数字。
  • 好吧,试试strPattern = "(?:^|\D)(\d{7})(?!\d)" 然后s = s & " Word: " & match.SubMatches(0) & " "。关键是您需要使用match.SubMatches(0) 迭代所有子匹配,然后您可以检查哪个是最大的。
  • 对于模式你能不能只使用\d{7}
  • @SJR \D 的原因是不要从更大的数字中提取 7 位数字。

标签: regex excel vba


【解决方案1】:

我建议使用以下模式:

strPattern = "(?:^|\D)(\d{7})(?!\d)"

然后,您将能够通过match.SubMatches(0) 访问捕获组#1 的内容(即使用正则表达式的(\d{7}) 部分捕获的文本),然后您可以检查哪个值最大。

模式详情

  • (?:^|\D) - 匹配字符串开头 (^) 或非数字 (\D) 的非捕获组(不创建任何子匹配)
  • (\d{7}) - 捕获组 1 匹配 7 个数字
  • (?!\d) - 如果 7 位数字之后有一个数字,则匹配失败。

【讨论】:

  • 很好的解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-12
  • 1970-01-01
相关资源
最近更新 更多