Home » excel » regex – Excel VBA Find & Replace Text In A String With Loop

regex – Excel VBA Find & Replace Text In A String With Loop

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m trying to replace all the text in a string between the pattern “&CC[number]:[number]” and replace it with a “==”.

Here is the string. "T &CC3:5 Q8 Party/ Self-Identify&CC6:8 Male&CC9:11 Female&CC12:15 Q1 Vote"

This is what I need it to look like T &CC3:5==&CC6:8==&CC9:11==&CC12:15==

I know I need to loop through this string but I’m not sure the best way to set this up.

Dim stringOne As String
Dim regexOne As Object
Set regexOne = New RegExp

regexOne.Pattern = "([Q])+[0-9]"
regexOne.Global = False
stringOne = "T &CC3:5 Q8 Party/ Self-Identify&CC6:8 Male&CC9:11 Female&CC12:15 Q1 Vote"

Debug.Print regexOne.Replace(stringOne, "==")
End Sub

I have also explored using this regular expression regexOne.Pattern = "([&])+[C]+[C]+[0-9]+[:]+[0-9]"

I plan to eventually set the variable stringOne to Range("A1").Text

How to&Answers:

You could simplify the pattern a bit and use a capturing group and a positive lookahead

(&CC[0-9]+:[0-9]+).*?(?=&C|$)

Explanation

  • ( Capture group 1
    • &CC[0-9]+:[0-9]+ Match &CC 1+ digits, : and 1+ digits
  • ) Close group
  • .*? Match 0+ times any char except a newline non greedy
  • (?=&C|$) Positive lookahead, assert what is directly on the right is either &C or the end of the string

Regex demo

In the replacement use the first capturing group followed by ==