2016-04-19 9 views
1

私は同様の質問にbeen asked beforeがあり、答えたことを認識していますが、その答えで提案された解決策を試しても問題は解決しません。正規表現のキャプチャからの改行を除外

複数行の文字列を複数の単一行に区切り、改行を含む空白を整えたExcelマクロを作成したいとします。これは私のコードです:

Sub testRegexMatch() 
    Dim r As New VBScript_RegExp_55.regexp 
    Dim str As String 
    Dim mc As MatchCollection 
    r.Pattern = "[\r\n\s]*([^\r\n]+?)[\s\r\n]*$" 
    r.Global = True 
    r.MultiLine = True 
    str = "This is a haiku" & vbCrLf _ 
     & "You may read it if you wish " & vbCrLf _ 
     & " but you don't have to" 
    Set mc = r.Execute(str) 
    For Each Line In mc 
     Debug.Print "^" & Line & "$" 
    Next Line 
End Sub 

予想される出力:

^This is a haiku$ 
^You may read it if you wish$ 
^but you don't have to$ 

実際の出力:私はRegex101で同じことを試してみたが、これは正しいキャプチャを表示するように表示されます

^This is a haiku 
$ 
^ 
You may read it if you wish 
$ 
^ 
    but you don't have to$ 

、それはVBAの正規表現エンジンの奇抜でなければなりません。

アイデア?

+1

うん、* *(= 'SubMatches'が)ここに言葉でキャプチャします。あなたは試合自体をつかんでいます。 '.SubMatches(0)'部分文字列にアクセスしてください。 –

+1

'\ s'を使用しているときは、' \ n'と '\ r'の必要は何ですか?? vbaでは' \ s'は別の扱いですか? – rock321987

+0

Wiktorに感謝の意を表します。答えとして投稿してください。 – jsheeran

答えて

1

あなただけSubMatches()を介して捕捉値にアクセスする必要があります。

正規表現が実行されると部分正規表現が括弧をキャプチャで囲まれているとき、ゼロ個以上のサブマッチが発生することができます。 SubMatchesコレクション内の各アイテムは、正規表現によって検出され、キャプチャされた文字列です。

Sub DemoFn() 
    Dim re, targetString, colMatch, objMatch 
    Set re = New regexp 
    With re 
    .pattern = "\s*([^\r\n]+?)\s*$" 
    .Global = True    ' Same as /g at the online tester 
    .MultiLine = True   ' Same as /m at regex101.com 
    End With 
    targetString = "This is a haiku " & vbLf & " You may read it if you wish " & vbLf & " but you don't have to" 
    Set colMatch = re.Execute(targetString) 
    For Each objMatch In colMatch 
    Debug.Print objMatch.SubMatches.Item(0) ' <== SEE HERE 
    Next 
End Sub 

それは出力します:

は、ここに私のデモです

This is a haiku 
You may read it if you wish 
but you don't have to 
+0

空白のマッチングに関連する不要な文字クラスを削除するように更新されました。 –

関連する問題