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

编写带排除规则的正则表达式UDF,匹配含特定字符的Mod*字符串变体

修正VBA RegexMatch UDF的正则表达式

需求规则

  • 自定义函数RegexMatch返回True的条件:
    1. 单元格文本包含Modif*、Moder*或Modr*开头的单词(如modified、moderate、modification)
    2. 同时存在Mod*开头的内容后跟指定单个字符(示例为"A",支持Mod A、Mod_A、Module xx A、Modules (A & B)这类格式)
  • 仅满足第一条但无符合要求的Mod*+指定字符时,返回False

示例验证表格

项目描述RegexMatch预期结果
new modified of module A 1TRUE
new modification of mod ATRUE
new moderate of mod_ATRUE
to modules (A & B)TRUE
new modified and moderate A 1FALSE
new modification of AFALSE
new moderate of modifyFALSE
to modules (D & E)FALSE

当前代码问题

现有正则\b[M]od(?!erate).*\b[" & tbx2 & "]\b存在以下缺陷:

  • 负向预查(?!erate)错误排除了包含moderate的合法场景
  • 未校验是否存在Modif*/Moder*/Modr*类单词
  • 指定字符的匹配逻辑过于严格,无法匹配Mod_A这类下划线连接的场景

修正后的代码

Public Function RegexMatch(str As String) As Boolean
    Dim targetChar As String: targetChar = "A" ' 可替换为ActiveSheet.TextBox2.Value
    Static re As New RegExp
    
    With re
        .IgnoreCase = True
        ' 正则逻辑:同时满足两个正向预查条件
        .Pattern = "^(?=.*\bMod(?:if|er|r)\w*)(?=.*\bMod\w*(?:[\W_]+)" & targetChar & "\b).*"
        RegexMatch = .Test(str)
    End With
End Function

正则表达式说明

  • ^(?=.*\bMod(?:if|er|r)\w*):正向预查,确保文本中存在以Modif/Moder/Modr开头的完整单词
  • (?=.*\bMod\w*(?:[\W_]+)" & targetChar & "\b):正向预查,确保存在以Mod开头的内容,后跟非单词字符(空格、括号等)或下划线,最终匹配到指定目标字符(且目标字符处于单词边界,避免匹配类似AB中的A)
  • .*:匹配任意剩余字符,不影响预查的条件验证

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 14:40:45