正则表达式模式选择了正确的子字符串,但在 运行 宏 vba 时抛出错误

RegEx pattern selects the proper substring but throws error when running macro vba

我试图用正则表达式删除两个字符串中逗号 , 之后的所有内容,前面是 [(左括号)和 ?(问号) .

我有这样的输入:

Together, Let's End Their War: Promoting a Culture of Health among Veterans on the Gulf - How strongly do you value your relationship with [Field-2]?

Together, Let's End Their War: Promoting a Culture of Health among Veterans on the Gulf - During the Clinical Scholars Program, with [Field-2], have you partnered new project(s) other than your team's Wicked Problem Impact Project?

所以我想删除第一个字符串中的 ? 和第二个字符串中的以下

, have you partnered new project(s) other than your team's Wicked Problem Impact Project?

我想结束

Together, Let's End Their War: Promoting a Culture of Health among Veterans on the Gulf - How strongly do you value your relationship with [Field-2]

Together, Let's End Their War: Promoting a Culture of Health among Veterans on the Gulf - During the Clinical Scholars Program, with [Field-2]

我有 (?<=]),\s*([^,])+|\?

这个模式似乎捕捉到了我想要的东西

但是当我 运行 我的宏时,我得到 Method 'Replace' of object 'IRegEep2' failed

https://regex101.com/r/c9lDYD/1

我的宏 运行 许多其他正则表达式模式都没有问题,所以不确定问题出在哪里。

Sub findReplace()
Dim outArray As Variant
Dim regEx As New RegExp
Dim ws As Worksheet
Dim i As Long

  Dim strPattern As String: strPattern = "(?<=]),\s*([^,])+|\?"
  Dim strReplace As String: strReplace = ""
        
  With regEx
    .Global = True
    .MultiLine = True
    .IgnoreCase = False
    .Pattern = strPattern
 End With
    
 Set ws = ThisWorkbook.Sheets("Helper_1Filted")

 With ws.Range("K1:K50")
    
      outArray = .value
      For i = 1 To UBound(outArray, 1)
          outArray(i, 1) = regEx.Replace(outArray(i, 1), strReplace)
      Next i
        
      .value = outArray
        
  End With
    
End Sub

我认为 vba 不支持 lookbehind,但是如果问号应该出现在匹配逗号和方括号之间的部分之后,您可以使用没有交替的捕获组 | .

当使用交替 | 时,问号将匹配字符串中的任何位置。

您可以使用捕获组和 negated character class [^

在替换使用组1中</code></p> <pre><code>(,[^\]\[,]*\[[^\]\[]*])[^?]*\?

  • ( 捕获 组 1
    • , 匹配逗号
    • [^\]\[,]* 匹配除逗号或 []
    • 之外的任何字符 0+ 次
    • \[[^\]\[]*] 匹配来自 [...]
  • ) 关闭组 1
  • [^?]* 匹配除问号以外的任何字符 0 次以上
  • \?匹配问号

Regex demo

或带有可选捕获组的较短版本:

(\])(?:,\s*[^,]+)?\?

Regex demo

检查了一下,可能是目前的VBA regex library 5.5不支持你代码中的回调函数,因为我测试的时候有警告

?<=]

稍微修改一下,它通过替换你例子中的问号来工作,虽然其他句子我可能不是100%确定,我只改变了开头部分,仅供参考。

(^]),\s*([^,])+|\?