Link to home
Start Free TrialLog in
Avatar of Dereck21
Dereck21

asked on

Finding Text and Inserting Text Please Help

First off I would like to thank everyone in advance, as I do know somethings about Visual Basic, I am mainly self taught and I admire all of your knowledge.  Heres my situation:

I have a text file about 100 pages long of pure non stop text, numbers, and symbols.  They are record extracts from a database.  I need a program that will go through the text file and after a certain text "text1" copy the digits between "text1" and "text2".  Then it must paste what it copied after the very next "text3".  Then if must move on until it finds "text1" again which will be a few lines further down and repeat the whole process.  "text1", "text2" and "text3" are contants.  However the number of characters that it needs to copy and paste will change each time.

Any help is greatly appretiated.
ASKER CERTIFIED SOLUTION
Avatar of rspahitz
rspahitz
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of rdrunner
rdrunner

I would solve this with regular expressions...

Lemme slap an example together :)



Here it is :

Private Sub Command1_Click()
Dim myRegExp As New RegExp
Dim myMatches As MatchCollection
myRegExp.Global = True   'whole text not just 1st time
myRegExp.IgnoreCase = True 'ignore case
myRegExp.Pattern = "(text1)([0-9]*)(text2)(.*)(text3)" 'Ok find some place that holds text1 , followed by some digits, followed by text2, followed by anything, followed by text3
Set myMatches = myRegExp.Execute(RichTextBox1.Text)
Debug.Print myMatches.Count
RichTextBox1.Text = myRegExp.Replace(RichTextBox1.Text, "$1$2$3$4$5$2")
End Sub

Some remarks about this string :
"(text1)([0-9]*)(text2)(.*)(text3)"
(text1) = your 1st token you wish to find (refference in replace as $1)
([0-9]*) - a number that has unlimit digits not just 2 ;) - but also 0 digits ... * can be replaced by + to match more then one digit - this is $2 in the replace string
(text2) = your 1st token you wish to find (refference in replace as $3)
(.*) = anything between text2 and text3 . is a wildcard and * a multiplayer (zero or more) again -> $4
(text3) = your 1st token you wish to find (refference in replace as $5) The token where you want to insert stuff after

Hope this helps

Some things you might want to add to the string:

-it expects NOTHING between text1 and the number so it wont find "text1 234" it will only find "text1234" - fill in what really is there ;)
-same about text2 -> "234text2" will match and "234 text2" wont match
-(.*) this will only match everything on that line i THINK
(to match more then one line you need the latest msScripting runtime) - my pc only has the "old" regexp here . it has no multiline property)


Hope this helps ;)
Avatar of Dereck21

ASKER

Thanks, forgot about awarding the points!