【问题标题】:how to do a replace within a replace match using vba regex如何使用 vba 正则表达式在替换匹配中进行替换
【发布时间】:2020-07-13 23:03:12
【问题描述】:

我需要替换一些字符,但前提是它们在括号内。所以假设下面的例子

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)

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

我尝试了以下内容,但我无法像我喜欢的那样处理正则表达式匹配。关于如何最好地解决它的任何替代方案或见解?

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

【问题讨论】:

    标签: regex ms-access vba


    【解决方案1】:

    给你,

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

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

    DEMO

    【讨论】:

    • 感谢 Raj,不幸的是,这在 VBA 中不起作用,因为它不喜欢没有实际内容的匹配(我猜,不是真正的专家 tbh)。 VBA 不支持 Regex.split,这使得它更加复杂
    猜你喜欢
    • 2012-05-16
    • 1970-01-01
    • 2015-11-30
    • 2012-09-28
    • 1970-01-01
    • 2018-03-23
    • 1970-01-01
    • 2013-12-06
    • 2021-04-10
    相关资源
    最近更新 更多