regex - 如何使用基于正则表达式条件的分隔符在 VBA 中拆分数组?
问题描述
我有这样的输入:
apple, orange, (pear, banana, grape), mango
我想拆分为:
apple
orange
(pear, banana, grape)
mango
我不完全理解正则表达式,但我想我会使用我在这里找到的 ,(?![^()]*)) - Java split string on comma(,) 除非在括号 () 之间
我正在使用 VBA,所以如果我将输入存储在一个数组中,我通常会这样做:
array = Split(string, ",")
但这会产生如下结果:
apple
orange
(pear
banana
grape)
mango
我不想要。
我很确定我可以找到一种方法来替换 ( 和 ),使它们从输出中消失,但我不知道如何将我的正则表达式字符串逻辑提供给我的 VBA 公式。
我认为这样的事情会起作用:
array = Split(string, ",(?![^()]*\))")
但事实并非如此。我确实启用了“Microsoft VBScript Regular Expressions 5.5”参考,但它似乎没有帮助。
任何建议表示赞赏。
谢谢,
解决方案
正则表达式的替代方案:
Sub mytry()
Dim str As String
str = "apple, orange, (pear, banana, grape), mango "
Dim perenSplt() As String
perenSplt = Split(Replace(str, ")", ")("), "(")
str = ""
Dim i As Long
For i = LBound(perenSplt) To UBound(perenSplt)
If InStr(perenSplt(i), ")") Then
perenSplt(i) = "(" & Replace(perenSplt(i), ",", "|")
End If
str = str & perenSplt(i)
Next i
Dim finalSplt() As String
finalSplt = Split(str, ",")
For i = LBound(finalSplt) To UBound(finalSplt)
If InStr(str, "(") > 0 Then
finalSplt(i) = Trim(Replace(finalSplt(i), "|", ","))
Else
finalSplt(i) = Trim(finalSplt(i))
End If
Next i
ActiveSheet.Range("A1").Resize(,UBound(finalSplt) + 1) = finalSplt
End Sub
推荐阅读
- scala - 如何知道 typeSignature 属性中的类型是否是指扩展某个类的任何类?
- python - 无法显示使用 python 在 GUI 中输入的所有信息
- .net-core - 网络摄像头到 .Net Core 服务器到 HTML 浏览器
- android - 测试TransitionAPI 总是导致广播完成:结果=0
- java - 如何从页面对象文件中分离网页元素
- php - 所有数据的默认加载,然后使用表单过滤表
- postgresql - Select PostgreSQL 中的条件替换
- javascript - 发送更新的父状态时反应子道具不更新
- javascript - 如何在 C# 中清除 javascript SessionStorage
- ruby - Cookbook 的深度依赖需要一个不可用的 Ruby 版本。如何通过 Chef for Amazon Linux 规避?