PDA

View Full Version : Replace only once on a line



HJ Norman
10-06-2010, 04:26 AM
I want to run this stuff
.Text = "([0-9]{1,3})[ ]"
.Replacement.Text = "(2, 28, \1, '"

on lines such as
1 Simple string 2 matching is 3 probably the 4 most basic

replacing only the first digit, ie, 1 in this case, without affecting the other numbers belonging to the same line.

With regex, inserting "^" at the beginning helps; but I'm stuck with Word.

macropod
10-06-2010, 04:39 AM
Hi HJ Norman,

For anything other than the first paragraph in the document, you could use:
Find = "([!0-9]{1,})([0-9]{1,3})([!^13]{1,}^13)"
Replace = "\1'replacement string'\3

HJ Norman
10-06-2010, 05:20 AM
Thankful as I am for your reply, I'm working on UTF-8 text files (generated by Word) with no other marks but pilcrows, and I can't get your code to work.

macropod
10-06-2010, 02:51 PM
Hi HJ Norman,

OK, assuming each paragraph starts with a number, try:
Find = "([0-9]{1,3})([!^13]{1,}^13)"
Replace = "'replacement string'\2

HJ Norman
10-07-2010, 01:27 AM
Hello again macropod!
I tried your lines. No text was changed!
Seems like I'm missing out on something here.
With tRange.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "([0-9]{1,3})([!^13]{1,}^13)"
.Replacement.Text = "(2, 28, \1, '\2"
.MatchWildcards = True
.Execute Replace:=wdReplaceAll
End With

Thanks for all your efforts.

macropod
10-07-2010, 02:48 PM
Hi HJ Norman,

Have you checked tRange's contents (eg Msgbox .tRange.text)? Also, the Find/Replace code, which looks for an end-of-paragraph marker, won't work if the affected paragraphs are in a table and the end-of-cell marker ends the paragraph. In that case, you'd do better to use something like:

Dim oPara As Paragraph
For Each oPara In tRange.Paragraphs
With oPara.Range.Words
If IsNumeric(.First) Then
With .First
.InsertAfter ", '"
.Characters.Last.Delete
.InsertBefore "(2, 28, "
End With
End If
End With
Next
Edit: swapped insertbefore & insertafter lines, added 'delete' to remiove trailing space.

HJ Norman
10-08-2010, 05:15 PM
This one works! I had switched back to regular regex using other progs. Now I better get back on track.
"If IsNumeric(.First)" is really a neat one.
Thank you, macropod for your time and effort and care.