• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

Remove before substrings using regex

YasserKhalil

Well-Known Member
Hello everyone
I have some strings like that
" Please take care nOHello fxExperts Excel"
And I have array of substrings that I want to use to remove the strings before any of these substrings

a = Array("fx", "TD", "nO")

So As for the example the expected output would be : "Experts Excel"
I need the regex pattern to do that task please?

The substrings in the array are case sensitive ..
 
You can do this without regexp as well. Following is lightly tested.

1. Put it in a VBA general module.
2. Insert like normal formula e.g. for cell A1 it will be:
=rgExReplace(A1)
Code:
Public Function rgExReplace(rng As Range) As String
Dim a
Dim rgEx As Object 'RegExp
Dim strVal As String
a = Array("fx", "TD", "nO")
Set rgEx = CreateObject("VBScript.RegExp")
rgEx.IgnoreCase = False
strVal = rng.Value
For i = LBound(a) To UBound(a)
    rgEx.Pattern = "(.)+" & a(i)
    strVal = rgEx.Replace(strVal, "")
Next i
rgExReplace = strVal
Set rgEx = Nothing
End Function

Edit: I thought I will post the non regex option as well. So here it is:
Code:
Public Function ReplaceStrings(rng As Range) As String
Dim i As Long, j As Long, posn As Long
Dim strVal As String
Dim a: a = Array("fx", "TD", "nO")
strVal = rng.Value
For i = LBound(a) To UBound(a)
  j = IIf(InStrRev(strVal, a(i), -1, vbBinaryCompare) > 0, InStrRev(strVal, a(i), -1, vbBinaryCompare) + Len(a(i)), 0)
  If posn < j Then posn = j
Next i
If posn > 0 Then ReplaceStrings = Mid(strVal, posn, Len(strVal))
End Function
 
Last edited:
Back
Top