2017-08-16 39 views
0

我想從字符串(使用VBA)返回5個連續數字。正則表達式 - 返回連續數字的確切數量

基於此職位Regex我使用的模式爲[^\d]\d{5}[^\d],但是這會在緊接目標5位數前後採集單個字母並返回h92345W(來自「... South92345West」)。

如何修改只返回5個連續數字:92345

Sub RegexTest() 

    Dim strInput As String 
    Dim strPattern As String 

    strInput = "9129 Nor22 999123456 South92345West" 

    'strPattern = "^\d{5}$" 'No match 

    strPattern = "[^\d]\d{5}[^\d]" 'Returns additional letter before and after digits 
            'In this case returns: "h12345W" 

    MsgBox RegxFunc(strInput, strPattern) 

End Sub 


Function RegxFunc(strInput As String, regexPattern As String) As String 

    Dim regEx As New RegExp 
    With regEx 
     .Global = True 
     .MultiLine = True 
     .IgnoreCase = False 
     .Pattern = regexPattern 
    End With 


    If regEx.test(strInput) Then 
     Set matches = regEx.Execute(strInput) 
     RegxFunc = matches(0).Value 
    Else 
     RegxFunc = "not matched" 
    End If 

End Function 

回答

2
([^\d])(\d{5})([^\d]) 

您可以使用此正則表達式,匹配的條件應該是在第二組

+0

我得到相同的結果「h92345W」 –

+0

你選擇第二組? – marvel308

+0

嘗試添加匹配(0).SubMatches(2)或匹配(0).SubMatches(1),我不確定語法 – marvel308

2

您需要使用一組:

"[^\d](\d{5})[^\d]" 

然後是電話號碼將是第一集團。不確定分組的VBA語法。

+0

我得到相同的結果「h92345W」 –