Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lookbehind on regex for VBA?

Is there a way to do negative and positive lookbehind in VBA regex?

I want to not match if the string starts with "A", so I am currently doing ^A at the start of the pattern, then removing the first character of match(0). Obviously not the best method!

I am using the regExp object.

like image 331
Django Doctor Avatar asked Feb 05 '12 15:02

Django Doctor


People also ask

What is Lookbehind in regex?

Lookbehind, which is used to match a phrase that is preceded by a user specified text. Positive lookbehind is syntaxed like (? <=a)something which can be used along with any regex parameter. The above phrase matches any "something" word that is preceded by an "a" word.

Can I use Lookbehind regex?

The good news is that you can use lookbehind anywhere in the regex, not only at the start.

Does VBA support regex?

RegEx stands for “Regular Expression” in VBA Excel and is a sequence of characters that defines the search pattern for finding a specific pattern of characters in a string of values. So, in a simple word, we can create a regular expression pattern and use it to search for the string of that pattern.

Does SED support Lookbehind?

I created a test using grep but it does not work in sed . This works correctly by returning bar . I was expecting footest as output, but it did not work. sed does not support lookaround assertions.


1 Answers

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
    
like image 89
brettdj Avatar answered Sep 20 '22 05:09

brettdj