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

如何在VBA中提取带转义引号的字符串子串?

VBA 提取包含转义引号(")的子串解决方案

实现思路

利用VBA的正则表达式对象,匹配从第一个"开始到最后一个"结束的完整子串,确保包含中间所有转义引号内容。

代码实现

方法1:早期绑定(需引用库)

  1. 打开VBA编辑器(按Alt+F11),依次点击「工具」→「引用」,勾选「Microsoft VBScript Regular Expressions 5.5」。
  2. 复制以下代码:
Function ExtractQuotedSubstring(inputStr As String) As String
    Dim regEx As New RegExp
    Dim matches As MatchCollection
    
    ' 正则规则:匹配第一个"到最后一个"之间的所有内容,包含首尾的"
    regEx.Pattern = "".*""
    regEx.Global = False ' 只匹配目标完整子串
    regEx.MultiLine = False
    
    Set matches = regEx.Execute(inputStr)
    If matches.Count > 0 Then
        ExtractQuotedSubstring = matches(0).Value
    Else
        ExtractQuotedSubstring = "" ' 无匹配时返回空字符串
    End If
End Function

方法2:后期绑定(无需引用库)

如果不想添加库引用,可使用后期绑定方式:

Function ExtractQuotedSubstring(inputStr As String) As String
    Dim regEx As Object
    Dim matches As Object
    
    Set regEx = CreateObject("VBScript.RegExp")
    regEx.Pattern = "".*""
    regEx.Global = False
    regEx.MultiLine = False
    
    Set matches = regEx.Execute(inputStr)
    If matches.Count > 0 Then
        ExtractQuotedSubstring = matches(0).Value
    Else
        ExtractQuotedSubstring = ""
    End If
End Function

示例用法

在VBA过程中调用测试:

Sub TestExtract()
    Dim originalStr As String
    Dim resultStr As String
    
    originalStr = "I open my eyes and said "hello to the "world""
    resultStr = ExtractQuotedSubstring(originalStr)
    
    ' 输出结果:"hello to the "world"
    Debug.Print resultStr
End Sub

正则表达式说明

  • ":匹配转义引号的字面量
  • .*:匹配任意字符(除换行符)零次或多次,结合MultiLine = False会匹配到字符串末尾的最后一个"
  • 整个表达式".*"精准捕获从第一个转义引号开始到最后一个转义引号结束的完整目标子串

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 04:40:24