代码之家  ›  专栏  ›  技术社区  ›  garek007

如何在Excel中的URL中获取介于二者之间的数字[已关闭]

  •  -1
  • garek007  · 技术社区  · 7 年前

    我试图在URL中提取4、5或6个数字。这个数字在URL中并不总是出现在同一个位置,有时它们位于第四位,有时位于第五位,有时,它们后面有一群狼吞虎咽的人。下面是一些示例。

    enter image description here

    我有一些VBA,我从一个 previous post ,但正如您所看到的,它在一些URL上出现了故障(上图)。我如何修改它,或者是否有一个公式可以用来始终返回右列中突出显示的数字?

    Public Function listNum(Myrange As Range) As String
        Dim regEx           As Object
        Dim inputMatches    As Object
        Dim regExString     As String
        Dim strInput        As String
        Dim a               As Byte
    
        Set regEx = CreateObject("VBScript.RegExp")
    
        With regEx
            .Pattern = "([0-9]{3,7})"
            .IgnoreCase = True
            .Global = True
            s = Myrange.Value
            Set inputMatches = .Execute(s)
    
            If regEx.Test(s) Then
                listNum = .Replace(s, "~")
                a = InStr(1, listNum, "~", vbTextCompare)
                listNum = Mid(s, a, Len(s) - (Len(listNum) - 1))
            Else
                listNum = ""
                'listNum = s 'takes entire contents of cell and puts it in, we do not want that
            End If
        End With
    End Function
    

    更新:显然,它们并不总是在两个斜杠之间,但看起来它们总是5个字符,这里还有两个URL。我们又开始营业了!

    /listings/?action=display&listingid=31221
    /es-gl/listings/?action=display&listingid=30931&menuid=706&hit=1
    
    4 回复  |  直到 6 年前
        1
  •  2
  •   Srdjan M.    7 年前

    数字位于字符串的末尾和后面 /? . 因此:

    正则表达式 : (?<=\/)\d+(?=\/\?|\/$)|(?<=listingid=)\d+

    细节:

    • + 一次和无限次之间的匹配
    • (?<) (?<=) 积极前瞻
    • $ 断言字符串末尾的位置
    • |

    RegEx demo

        2
  •  1
  •   tigeravatar    7 年前

    作为配方解决方案,这应该适用于您:

    =--MID(A1,MATCH(TRUE,INDEX(ISNUMBER(--MID(SUBSTITUTE(A1,"-","|"),ROW(INDIRECT("1:"&LEN(A1)-4)),5)),),0),5)
    
        3
  •  1
  •   Ansgar Wiechers    7 年前

    如果您正在查找数字,为什么不简单地将两个正斜杠之间的数字匹配为一个捕获组,然后提取该组?

    Set re = New RegExp
    re.Pattern = "/(\d{3,7})/"
    
    For Each m In re.Execute(s)
        listNum = m.Submatches(0)
    Next
    
        4
  •  0
  •   Gary's Student    7 年前

    没有 正则表达式 :

    Public Function GetNumber(s As String) As String
        Dim a, L As Long
        ary = Split(s, "/")
        For Each a In ary
            L = Len(a)
            If L > 3 And L < 7 And IsNumeric(a) Then
                GetNumber = a
                Exit Function
            End If
        Next a
        GetNumber = ""
    End Function
    

    enter image description here

    将提取4、5或6位数字。