Replacing text via code

R

Roger Spencelayh

I need to replace text so that where I have a digit followed by a
hyphen followed by a digit (e.g. 1-2), the hyphen gets replaced by an
en-dash. I can find the any digit using ^#, but of course I can't then
use that in the replacement. Is there any way other than moving within
the found text to find the hyphen then overtyping it with the en-dash?
Just seems so clunky.

Thanks for any help.
 
G

Greg

Roger.

Something like:

Sub ScratchMacro()

Dim oRng As Word.Range
Set oRng = ActiveDocument.Range
With oRng.Find
.MatchWildcards = True
.Text = "([0-9])-([0-9])"
.Replacement.Text = "\1^=\2"
.Execute Replace:=wdReplaceAll
End With
End Sub
 
R

Roger Spencelayh

Something like:
<Snip Code>

Thanks for that Greg. Works great.

I follow it down to the line .Replacement.Text = "\1^=\2"

What do the \1 and \2 mean and how do I find out about these codes? Is
this something specific to Regular Expressions or is it part of the
Word syntax?
 
G

Greg Maxey

Roger,

The parens around the first "([0-9])" is a group (group 1). The parens
around the second "([0-9])" is a group (group 2). In the replace with field
you are putting back the found content of group 1 "\1" the en dash "^=" and
the content of found group 2 "\2"

The a description of most of the special wildcard codes can be found in Word
Help. Here is an excellent reference by fellow MVP Graham Mayor:
http://www.gmayor.com/replace_using_wildcards.htm
 
R

Roger Spencelayh

The parens around the first "([0-9])" is a group (group 1). The parens
around the second "([0-9])" is a group (group 2). In the replace with field
you are putting back the found content of group 1 "\1" the en dash "^=" and
the content of found group 2 "\2"

Twas the Grouping capability I wasn't aware of, and I've now found it in the
help. Works great when you know what you're looking for said:
The a description of most of the special wildcard codes can be found in Word
Help. Here is an excellent reference by fellow MVP Graham Mayor:
http://www.gmayor.com/replace_using_wildcards.htm

I'll have a look for that this evening. Thanks again.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top