首页 > 解决方案 > 在 Word 文档中搜索(单/双引号)之间的文本

问题描述

我正在尝试获取(单/双引号)中存在的数据列表

输入数据为:

拉维问拉杰“你好吗?” 和“你去哪儿了”。Raj 回答说:“我很好,Ravi,‘你好吗’和‘你是怎么认识这个人的?’”

预期输出为:

(需要考虑边界引号,并且应该在其中嵌入单/双引号字符)

请在 Word VBA 中为此提供有关 RegExp 的建议。

我正在尝试以下代码但没有成功:

Sub Test()
    Dim mystring As RegExp
    Dim mydata As MatchCollection

    Set mystring = New RegExp
    mystring.Pattern = "\s("".*"")\s"
    mystring.Global = True
    Set mydata = mystring.Execute(ActiveDocument.Range)


    For Each wrd In mydata
        MsgBox wrd
    Next wrd

End Sub  

标签: regexvbams-word

解决方案


这应该有效:

".+?"|'.+?'

在线尝试

但是,这包括匹配项中的单引号/双引号,这似乎不是您的预期输出。不过,您可以使用 VBA 删除它们。

一个完整的 VBA 示例:

Sub Test()
    Dim re As RegExp
    Dim matches As MatchCollection
    Dim m As Match

    Set re = New RegExp
    re.Pattern = """.+?""|'.+?'"
    re.Global = True
    Set matches = re.Execute(ActiveDocument.Range)

    For Each m In matches
        'MsgBox m           ' With quotes.
        Dim parsed As String
        parsed = Mid$(m, 2, Len(m) - 2)
        MsgBox parsed       ' Without quotes.
    Next m
End Sub

推荐阅读