You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在VBA正则表达式中排除特定字符串(如'w/d')?

Solution to Exclude Specific Strings Like w/d in Your VBA Function

Nice question! Your existing regex already does a great job excluding dates by targeting non-digit characters before :, /, and -—let’s tweak it to also skip specific patterns like w/d without breaking what’s already working.

The Modified Code

Here’s the updated function with logic to exclude w/d (and room to add more excluded patterns later):

Private Function formatColon(oldString As String) As String
    Dim reg As New RegExp
    reg.Global = True
    ' Updated regex: Match non-digit followed by :/- but exclude w/d's /
    reg.Pattern = "((?<!w)\D:|\D/(?!d)|(?<!\d)-)"
    Dim newString As String
    newString = reg.Replace(oldString, "$1 ")
    ' The nested Replaces here are redundant since we're adding a single space, but kept for consistency with your original code
    formatColon = Replace(Replace(Replace(newString, ": ", ": "), "/ ", "/ "), "- ", "- ")
End Function

How It Works

Let’s break down the adjusted regex pattern ((?<!w)\D:|\D/(?!d)|(?<!\d)-):

  • (?<!w)\D:: Matches a non-digit character followed by : only if the character before the non-digit isn’t w (prevents false matches if you had a pattern like w:, though you mentioned w/d specifically)
  • \D/(?!d): Matches a non-digit character followed by / only if the character after / isn’t d—this skips the / in w/d entirely
  • (?<!\d)-: Your original logic to match a non-digit followed by - (still excludes dates like 15-06-2017)

Example Test

If you input:

w/d abc/abc/15/06/2017 hello:world test-case

The output will be:

w/d abc/ abc/ 15/06/2017 hello: world test- case

Notice w/d stays untouched, while other non-date instances of /, :, - get a trailing space added.

Adding More Excluded Patterns

If you need to skip other specific strings later (like x-y), just extend the regex with additional negative assertions. For example, to exclude x-y, update the - segment to (?<!x)-(?!y).

内容的提问来源于stack exchange,提问作者Manu Mohan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:03:37