Regex 从正则表达式捕获中排除换行符

Regex 从正则表达式捕获中排除换行符,regex,excel,vba,Regex,Excel,Vba,我意识到类似的问题已经出现并得到了回答,但在我尝试了答案中提出的解决方案后,问题依然存在 我想编写一个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]+?)[\

我意识到类似的问题已经出现并得到了回答,但在我尝试了答案中提出的解决方案后,问题依然存在

我想编写一个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$
实际产量:

^This is a haiku
$
^
You may read it if you wish   
$
^
   but you don't have to$
我也尝试过同样的方法,但这似乎显示了正确的捕获,所以这一定是VBA的regex引擎的一个怪癖


有什么想法吗?

您只需通过以下方式访问捕获的值:

当执行正则表达式时,如果子表达式包含在捕获括号中,则可能会产生零个或多个子匹配。
子匹配
集合中的每个项都是正则表达式找到并捕获的字符串

这是我的演示:

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

是的,这里的单词是捕获(
子匹配)。你是在抢火柴。访问
.SubMatches(0)
子字符串。当您使用
\s
时,
\n
\r
的需要是什么?
\s
在vba中的处理方式不同吗?谢谢Wiktor,这就是诀窍-将其作为答案发布,我会接受。@rock321987:好的一点,我添加了\n\r,因为我一直在尝试对其进行修改以使其正常工作,但忘记将其删除。已更新以删除与空白匹配相关的不必要字符类。
This is a haiku
You may read it if you wish
but you don't have to