2017-12-05 20 views
0

VBAのlookbehindに関する質問がたくさんあります。問題は、正と負の先読みがありますが、VBA doesn't supportlookbehindsはまったくありません。VBA正規表現の一般的な正式な見解をシミュレートします

テキストから文字列を抽出するという非常に特殊な問題を解決しようとする多くの質問には、veryhelpfulがありました。これらの特定のケースには、workaroundsが提供されています。私の質問は、引数として正規表現のパターンを受け入れると結果の文字列で(必要がキャプチャされていない)接頭辞を省略している間に、目的のマッチグループを返すだけで検索を置き換える正のlookbehindをシミュレートVBで関数を書くことができます?

+0

あなたの答えは、キャプチャの仕組みに基づいたもう1つの通常の回避策です。さらに簡単に書くことができます。 –

答えて

0

次の関数は、この問題を満たすために、マッチする文字列、キャプチャできないプレフィックスの正規表現パターン、後続のキャプチャグループの正規表現パターンを受け入れます。

Function LookBehindRegex(ByVal inputText As String, nonCaptureRegex As String, _ 
    captureRegex As String) 

    'Non capturing lookbehind to retrieve reference preceded by a regex group 

    Dim regEx As New RegExp 
    Dim intermediate As String 
    Dim nonCaptureText As String 

    regEx.IgnoreCase = True 
    'First set the capture pattern to both regex groups, to capture the whole text 
    regEx.Pattern = "(" & nonCaptureRegex & ")" & "(" & captureRegex & ")" 
    'Store that 
    intermediate = regEx.Execute(inputText)(0) 
    'Next, set the pattern to only capture the non-capture regex 
    regEx.Pattern = nonCaptureRegex 
    'Store the non-capturable text from the intermediate result 
    nonCaptureText = regEx.Execute(intermediate)(0) 
    'Finally remove the non-capture text from the intermediate result 
    TestReg = Replace(intermediate, nonCaptureText, "") 

End Function 

制限事項:これは肯定的な視線をシミュレートするだけです。関連する正規表現モジュールは、VBプロジェクトへの参照として追加する必要があります。

関連する問題