作者:tmtony用Excel VBA 通过正则表达式从一串字符中提取所有数字或提取指定长度的数字有一个客户有这个需求,就帮忙做了2个函数废话少说,直接上代码
'基础版 提取字符中的所有数字Public Function MyGetNum(strSrc As String) As String Dim regex As Object Set regex = CreateObject("vbscript.regexp") With regex .Global = True .Pattern = "[^\d+]" '替换掉非数字 MyGetNum = .Replace(strSrc, "") End WithEnd Function
'升级版 只取连续的16位的数字Public Function MyGetNum2(strSrc As String) As String Dim regex As Object Dim matcher As Object Dim i As Integer Set regex = CreateObject("vbscript.regexp") With regex .Global = True .ignorecase = True .Pattern = "\d{16}" End With Set matcher = regex.Execute(strSrc) For i = 0 To matcher.Count - 1 Debug.Print matcher.Item(i) Next iEnd Function