如何在VBA正则表达式中排除特定字符串(如'w/d')?
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’tw(prevents false matches if you had a pattern likew:, though you mentionedw/dspecifically)\D/(?!d): Matches a non-digit character followed by/only if the character after/isn’td—this skips the/inw/dentirely(?<!\d)-: Your original logic to match a non-digit followed by-(still excludes dates like15-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

