Lookbehind on regex for VBA?

时光怂恿深爱的人放手 提交于 2019-11-26 23:06:07
brettdj

VBA offers positive and negative lookaheads but rather inconsistently not lookbehind.

The best example of using Regex with VBA that I have seen is this article by Patrick Matthews

[Updated example using Execute rather than Replace]

While I am not completely clear on your usage you could use a function like this with

  • skips any words starting with A
  • for all words not starting with a it returns everything from the second character on (using a submatch - the pattern inside ( and ) is submatch 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
    

How about putting the ^A in a non-captured group and using the SubMatches property of the Match object to get your matched value?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!