Search code examples
vbaexcel-2013

How do I replace a sequence of characters but not if they are part of a bigger word?


Say I want to replace the string BASE with STUFF but not in BASELESS or BASED. Here is the original string:

THE BASE OF THIS STATEMENT IS A BASELESS BASE

and I want it to read:

THE STUFF OF THIS STATEMENT IS A BASELESS STUFF

I've got something like this

Dim myString As String : myString = "THE BASE OF THIS STATEMENT IS A BASELESS BASE"
myString = Replace(myString, "BASE ", "STUFF ")
If Right(myString, 4) = "BASE" Then
  myString= Left(myString,Len(myString)-4) & "STUFF"
End If

But is there a cleaner way?


Solution

  • Try this:

    Dim regEx
    Set regEx = New RegExp
    regEx.Pattern = "BASE(?!\w)"
    regEx.IgnoreCase = True
    regEx.Global = True
    myString= regEx.Replace(myString, "STUFF")