You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Word VBA中使用正则表达式提取单/双引号内的文本

Fixing VBA Regex to Extract Quoted Text with Nested Quotes

Got it, let's sort out your regex problem! The goal is to pull out text wrapped in single or double quotes, while allowing the opposite quote type to be nested inside—your current pattern isn't handling that at all, and has a syntax error to boot.

The Correct Regex Pattern

Here's a regex that will properly match quoted text with nested opposite quotes:

"([^"]*(?:'[^"]*')*[^"]*)"|'([^']*(?:"[^']*")*[^']*)'

Let me break this down so you understand how it works:

  • "([^"]*(?:'[^"]*')*[^"]*)" : Matches text wrapped in double quotes. Inside, it allows any characters that aren't double quotes, plus any number of single-quoted segments (so nested single quotes are fine).
  • | : Acts as an "or" operator to handle the single-quote case.
  • '([^']*(?:"[^']*")*[^']*)' : Matches text wrapped in single quotes, allowing nested double quotes using the same logic as the double-quote branch.

Updated VBA Code

Replace your existing Sub Test() with this code—it'll extract the actual content inside the quotes (not including the quotes themselves):

Sub ExtractQuotedText()
    Dim regex As RegExp
    Dim matches As MatchCollection
    Dim match As match
    Dim extractedText As String
    
    ' Initialize regex object
    Set regex = New RegExp
    regex.Pattern = """([^""]*(?:'[^""]*')*[^""]*)""|'([^']*(?:""[^']*"")*[^']*)'"
    regex.Global = True ' Match all occurrences
    regex.IgnoreCase = False ' Case-sensitive (adjust if needed)
    
    ' Execute regex on the active document's content
    Set matches = regex.Execute(ActiveDocument.Range.Text)
    
    ' Loop through matches and extract the inner text
    For Each match In matches
        ' Check which group has content (double-quote group is index 0, single-quote is index 1)
        If match.SubMatches(0) <> "" Then
            extractedText = match.SubMatches(0)
        Else
            extractedText = match.SubMatches(1)
        End If
        ' Show the extracted text (or add to a list/array instead)
        MsgBox extractedText
    Next match
End Sub

Key Notes on the Code:

  • We escaped double quotes in the pattern with an extra double quote ("") because VBA uses double quotes to wrap string literals.
  • The SubMatches property lets us grab the text inside the quotes (the parts captured by the parentheses in the regex). We check which submatch has content since each match will only trigger one of the two regex branches.

Testing with Your Example Input

For your input:

Ravi asked Raj "How are You?" and 'Where have you been'. Raj replied "Iam fine Ravi, 'How are you' and 'how did you know this person?'"

The code will output exactly the 3 items you expect:

  • How are You?
  • Where have you been
  • Iam fine Ravi, 'How are you' and 'how did you know this person?'

Edge Cases to Consider

  • This regex doesn't handle escaped quotes (like He said "I\"m here"). If you need to support escaped quotes, we'd need to adjust the pattern to account for that.
  • It assumes quotes are properly paired—unclosed quotes might lead to unexpected results.

内容的提问来源于stack exchange,提问作者Shabaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:38:33