How to Add a Character to the Beginning of Each Word?

Viewed 202

I am using the RegExp object in VBA. I have a string and would like to add a $ character to the beginning of each word.

For example, if my string is:

dog cat 1 rrr

I would like to convert it to:

$dog $cat $1 $rrr

In RegExp I learned that you should use $1 instead of \1 to indicate a capturing group.
I tried the following VBA code.

Dim newString as String
Dim reg_exp As New RegExp
reg_exp.Pattern = "(\b\w+\b)"
reg_exp.IgnoreCase = True
reg_exp.Global = True

newString = reg_exp.Replace("dog cat 1 rrr", "\$$1")  

In the replacement string I used \\$$1 where \\$ indicates $ and $1 indicates a capturing group.

The result was:

\\$1 \\$1 \\$1 \\$1 \\$1

Can anyone help me with the proper regular expression to use?

1 Answers

You do not need to match word boundaries on both ends of \w+, they are there implicitly.

Also, no need to wrap the whole pattern with capturing parentheses, since you can always use $& backreference in the replacement pattern to refer to this whole match value.

And the most important bit: to use a literal dollar symbol inside a replacement pattern, you need to escape it with another dollar sign, $$.

Use

reg_exp.Pattern = "\w+"

and

newString = reg_exp.Replace("dog cat 1 rrr", "$$$&")
Related