正则表达式从字符串中提取n位数字

时间:2015-07-24 14:03:48

标签: regex vba

这是我的代码:

Dim sPartIDNumberArray() As String
Dim strIn as String

...

Dim objRegex
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
 .Global = True
 .Pattern = "(\d{7})+"
sPartIDNumberArray = .Execute(strIn)
End With

FirstPartID = sPartIDNumberArray(1)
SecondPartID = sPartIDNumberArray(2)

我需要从文本字符串中提取两个7位数字,如

  

Punktschweissen \ 3-Blech \ 1384156 RE和1375188   ZB RE 20 PART 1

.Execute方法不应该在这里工作吗? 我需要FirstPartID = 1384156和SecondPartID = 1375188 提前谢谢

1 个答案:

答案 0 :(得分:0)

您无法将.Execute方法的结果分配给字符串数组。它返回IMatchCollection2类型的对象。

以下是应该有效的代码:

Sub reg()
    Dim objRegex As Object
    Dim regexMatches As Object
    Dim strIn As String
    Dim FirstPartID As String
    Dim SecondPartID As String


    strIn = "Punktschweissen\3-Blech\1384156 RE und 1375188 ZB RE 20 PART 1"


    Set objRegex = CreateObject("vbscript.regexp")
    With objRegex
        .Global = True
        .Pattern = "(\d{7})+"
        Set regexMatches = .Execute(strIn)
    End With

    FirstPartID = regexMatches(0)  'sPartIDNumberArray(1)
    SecondPartID = regexMatches(1) 'sPartIDNumberArray(2)

End Sub