You need to enable JavaScript to run this app. 如何从带转义引号与换行符的VBA拼接字符串中提取APPLE
优惠活动
大模型
产品
解决方案
定价
更多

如何从带转义引号与换行符的VBA拼接字符串中提取APPLE

解决方案总览

你给出的字符串是带换行、缩进的单元素JSON数组结构,以下3种方案在VBA环境下均可稳定提取APPLE:


方案1:正则表达式(通用度最高,适配内容含特殊符号的场景)

不需要提前引用库,使用晚绑定即可直接调用,只要目标内容是字符串中唯一被双引号包裹的值就可以正确提取:

Function GetQuotedContent(inputStr As String) As String
    Dim regEx As Object
    Set regEx = CreateObject("VBScript.RegExp")
    With regEx
        .Global = False
        .Pattern = """([^""]+)"""
        If .Test(inputStr) Then
            GetQuotedContent = .Execute(inputStr)(0).SubMatches(0)
        End If
    End With
    Set regEx = Nothing
End Function

' 调用示例
Sub Test()
    Dim originStr As String
    originStr = "[" & vbCrLf & "  ""APPLE""" & vbCrLf & "]"
    Debug.Print GetQuotedContent(originStr) ' 输出 APPLE
End Sub

方案2:原生字符串处理(无额外依赖,适合固定格式场景)

如果你的字符串结构永远和示例一致,可以直接用原生字符串方法逐层处理,不需要依赖任何外部组件:

Sub ExtractWithNativeMethod()
    Dim originStr As String, temp As String, result As String
    originStr = "[" & vbCrLf & "  ""APPLE""" & vbCrLf & "]"
    
    ' 先移除所有换行、方括号
    temp = Replace(Replace(Replace(originStr, vbCrLf, ""), "[", ""), "]", "")
    ' 去除前后空格后,截取掉首尾的双引号
    temp = Trim(temp)
    result = Mid(temp, 2, Len(temp) - 2)
    
    Debug.Print result ' 输出 APPLE
End Sub

方案3:JSON解析(适合后续有扩展需求的场景)

如果后续需要处理同结构的多元素数组,可以直接用JSON解析逻辑处理,导入VBA-JSON模块到工程后直接取数组第一个元素即可:

Sub ExtractWithJson()
    Dim originStr As String, json As Object, result As String
    originStr = "[" & vbCrLf & "  ""APPLE""" & vbCrLf & "]"
    
    Set json = JsonConverter.ParseJson(originStr)
    result = json(1) ' VBA-JSON数组下标从1开始
    
    Debug.Print result ' 输出 APPLE
End Sub

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 09:27:01