search for strings separated by 1-n characters?

K

kaston

i want to do a regular expression search in a word doc that will let me
find
two strings separated by say 50 characters of any type or less,
assuming carriage returns are considered characters. the idea is to be
able to search a document for 2 words that are separated by other
unknown words but that are "close" to each other.

so if i want to find the strings "blah" and "ya"
i tried the expression blah?{1,50}ya hoping that the ?{1,50} would
specify
1-50 single characters of any type. but this finds blah and ya even if
they
are separated by many pages (hundreds of characters). what am i doing
wrong?

thanks,
kaston
 
D

Doug Robbins - Word MVP

You could do it with a macro containing the following code:

Dim Range1 As Range, Range2 As Range
Dim Word1 As String, Word2 As String, Spacing As Long, MaxSpace As Long
Word1 = InputBox("Enter the first word.")
Word2 = InputBox("Enter the second word.")
MaxSpace = Val(InputBox("Enter the maximum number of characters between the
words."))
Selection.HomeKey wdStory
Selection.Find.ClearFormatting
With Selection.Find
Do While .Execute(FindText:=Word1, Forward:=True, _
MatchWildcards:=False, Wrap:=wdFindStop, MatchCase:=False) = True
Set Range1 = Selection.Range
Set Range2 = Range1.Duplicate
Range2.End = ActiveDocument.Range.End
Spacing = InStr(Range2, Word2)
If Spacing > 0 And Spacing - Len(Word1) < MaxSpace Then
Range1.End = Range1.Start + Spacing + Len(Word2) - 1
Range1.Select
MsgBox "OK"
End If
Selection.Collapse wdCollapseEnd
Selection.MoveRight wdCharacter, 1
Loop
End With


--
Hope this helps.

Please reply to the newsgroup unless you wish to avail yourself of my
services on a paid consulting basis.

Doug Robbins - Word MVP, originally posted via msnews.microsoft.com
 
K

kaston

Doug said:
You could do it with a macro containing the following code:
whoa. thanks for the code. i've never used macros in word before but
i'll try it out.

do you know why my reg exp search didn't work though? i can't see what
i'm doing wrong
 
G

Greg Maxey

Kaston,

Weird yes.

Words Find feature is a little like water (runs in streams and takes the
path of least resistance).

Blah?{1,50}ya

Word finds Blah (its happy)
Word then finds 1 to 50 characters of anything (its happy)
Word then finds ya (its happy)

It doesnt care if there are 1 or 1,000,000 characters between that 50th
characer and ya. All it cares about is finding ya. If it exists it will be
happy to do so.

I don't know if there is a string that would meet your needs. Sorry.
 

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