【问题标题】:Lookbehind on regex for VBA?回顾 VBA 的正则表达式?
【发布时间】:2012-02-27 08:43:43
【问题描述】:

有没有办法在 VBA 正则表达式中进行消极和积极的后视?

如果字符串以“A”开头,我想不匹配,所以我目前在模式的开头执行 ^A,然后删除 match(0) 的第一个字符。显然不是最好的方法!

我正在使用 regExp 对象。

【问题讨论】:

  • 我假设您使用的是RegExp 对象?

标签: regex vba lookbehind negative-lookbehind


【解决方案1】:

VBA 提供正面和负面的前瞻,但不一致地不提供后瞻。

我见过的将 Regex 与 VBA 结合使用的最佳示例是 Patrick Matthews 的 this article

[使用Execute 而不是Replace 的更新示例]

虽然我不完全清楚你的用法,但你可以使用这样的函数

  • 跳过任何以 A 开头的单词
  • 对于所有不以 a 开头的单词,它会返回从第二个字符开始的所有内容(使用子匹配 - () 中的模式是子匹配 1 -

    Sub TestString()
    MsgBox ReducedText("cfat dcat")
    MsgBox ReducedText("Sat all over the hat again")
    End Sub
    
    
    Function ReducedText(strIn As String) As String
    Dim objRegex As Object
    Dim objRegMC As Object
    Dim objRegM As Object
    Dim strOut As String
    Set objRegex = CreateObject("vbscript.regexp")
    With objRegex
      .IgnoreCase = True
      'not needed if matching the whole string
      .Global = True
      .Pattern = "\b[^a\s]([a-z]+)"
      If .test(strIn) Then
          Set objRegMC = .Execute(strIn)
          For Each objRegM In objRegMC
            strOut = strOut & objRegM.submatches(0) & vbNewLine
          Next
          ReducedText = strOut
      Else
        ReducedText = "Starts with A"
      End If
    End With
    End Function
    

【讨论】:

    【解决方案2】:

    如何将 ^A 放在未捕获的组中并使用 Match 对象的 SubMatches 属性来获取匹配值?

    【讨论】:

    • 听起来很有趣。如何使用子匹配?
    猜你喜欢
    • 1970-01-01
    • 2023-02-22
    • 2018-01-02
    • 1970-01-01
    • 2021-03-21
    • 2015-11-21
    • 1970-01-01
    • 1970-01-01
    • 2011-01-25
    相关资源
    最近更新 更多