如何使用vba regex在替换匹配中进行替换

时间:2014-10-04 11:16:24

标签: regex vba access-vba

我需要替换一些字符,但只有当它们在括号内时才需要。因此,假设以下示例

this is a string (with comment), this is another string without comment, and this is a string (with one comment, and another one)

我需要能够根据逗号值拆分这句话。除了令人讨厌的事实,最后的评论还包含一个逗号,所以我的分裂有点受限。期望的结果必须如下

this is a string (with comment), 
this is another string without comment, 
and this is a string (with one comment, and another one)

我正在使用访问VBA,我的方法是首先隔离所有注释(括号内的内容),用不同的字符(比如管道符号)替换逗号,然后使用拆分或替换选项来拆分整句话。

我尝试的是如下所示,但我没有像我喜欢的那样处理正则表达式匹配。任何替代方案,或者对我如何最好地解决它的见解?

Function commentFixer(s As String, t As String) As String

't = token to be replaced, eg a comma

Dim regEx As New RegExp
Dim match As String
regEx.Global = True
p = "(\([^()]*\)*)"
'match all commented substrings
regEx.Pattern = p 

'below obviously doesn't work, as the match itself is not accepted as a character. Any way to deal with this ?

match = "$1" 'How can I store this in a variable to perform a replacement on the result ?
dim r as string 'replacement value

r = Replace(match, t, "|")

commentFixer = regEx.Replace(s, r)

End Function

Sub TestMe()

s = commentFixer("this is a string (with comment), this is another string without comment, and this is a string (with one comment, and another one)", ",")
Debug.Print s

'expected result : this is a string (with comment), this is another string without comment, and this is a string (with one comment| and another one)
End Sub

1 个答案:

答案 0 :(得分:0)

你走了,

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

组索引1和2包含您想要的字符串。

DEMO