如何在Excel中的两个/之间获取数字

时间:2018-01-24 22:05:57

标签: regex excel excel-vba vba

我正在尝试在URL中提取4,5或6个数字。这个数字并不总是出现在URL的同一个地方,有时它们处于第四位,有时是第五位,有时候,它们背后有一堆gobbledygook。下面是一些例子。

enter image description here

我有一些VBA,我是从previous post一起攻击的,但正如您所看到的那样,它会破坏某些网址(上图)。我如何修改它,或者是否有我可以使用的公式,以便始终在右栏中返回突出显示的数字?

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 个答案:

答案 0 :(得分:2)

数字位于字符串的末尾,位于/?之后。所以:

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

<强>详细信息:

  • +匹配一次且无限次
  • (?<)(?<=)肯定前瞻
  • $在字符串
  • 的末尾断言位置
  • |

RegEx demo

答案 1 :(得分:1)

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

Set re = New RegExp
re.Pattern = "/(\d{3,7})/"

For Each m In re.Execute(s)
    listNum = m.Submatches(0)
Next

答案 2 :(得分:1)

作为公式解决方案,这应该适合您:

=--MID(A1,MATCH(TRUE,INDEX(ISNUMBER(--MID(SUBSTITUTE(A1,"-","|"),ROW(INDIRECT("1:"&LEN(A1)-4)),5)),),0),5)

答案 3 :(得分:0)

没有 正则表达式

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位数字。