0
我需要替换一些字符,但只能在括号内。因此,假设以下示例如何在替换内使用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
感谢拉吉,不幸的是,这并不在VBA内(TBH我guees,而不是一个真正的专家)的工作,因为它不喜欢没有实际内容的匹配。 Regex.split在VBA中不受支持,这使得它更复杂 – Wokoman 2014-10-04 12:56:25
请参阅http://regex101.com/r/aP7aD5/3 – 2014-10-04 13:03:32