2017-08-16 8 views
0

文字列(VBAで作業中)から5桁の連続した数字を返したいと思います。正規表現 - 正確な桁数を返す

この記事Regexに基づいて、私はパターン[^\d]\d{5}[^\d]を使用していますが、これは目標の5桁の前と後に、すぐに単一の文字をピックアップし、h92345W(「South92345West ....」から)を返します。 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]" 

をそして数は最初のグループになります

どのように私は唯一の5つの連続した数字を返すように変更することができます。グループ化のVBA構文については不明です。あなたは、この正規表現を使用することができます

+0

にする必要があります私は同じ結果を得る「h92345W」 –

関連する問題