• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 219
  • Last Modified:

How to replace a string that is enclosed for a couple of tags

HI

Now I have a string like this "start-blablablablablabla-end" in a file, I need to replace the whole string but the deal is that the string between "start-" and "-end", is not always the same (content and size).

Regards
0
dimensionav
Asked:
dimensionav
1 Solution
 
VBClassicGuyCommented:
Assume your text string is in the declared text variable "txt".

Dim NewText As String

If Left(txt, 6) = "start-" And Right(txt, 4) = "-end" Then
   'do your string substitution here
   NewText = <whatever>
End If
0
 
slightwv (䄆 Netminder) Commented:
I would look at regular expressions.

My straight VB is pretty rusty but check out:
http://www.vb-helper.com/howto_regular_expression_replace_lines.html

You would want to replace:  "(start-).*(-end)" with whatever you needed.


>>If Left(txt, 6) = "start-" And Right(txt, 4) = "-end" Then

From the related question I believe that string can exist anywhere in a larger string.
0
 
Muhammad KhanManager, ITCommented:
Sub Macro1()
Set fso = CreateObject("Scripting.FileSystemObject")
Dim fileStream
Dim s
Dim ifrom
Dim ito
Dim sToReplace
Dim sToBeReplaced

Set fileStream = fso.OpenTextFile("c:\workshop\File1.txt", 1)
sToReplace = "just a test string"

s = fileStream.ReadAll
ifrom = InStr(1, s, "start-", vbTextCompare) + Len("start-")
ito = InStr(1, s, "-end", vbTextCompare)
sToBeReplaced = Mid(s, ifrom, ito - ifrom)
s = Replace(s, sToBeReplaced, sToReplace)

fileStream.Close
Set fileStream = fso.OpenTextFile("c:\workshop\File1.txt", 2)
fileStream.Write (s)
fileStream.Close
End Sub
0
 
Martin LissRetired ProgrammerCommented:
Const TESTDATA = "start-blablablablablabla-end"

Dim intStart As Integer
Dim intEnd As Integer

intStart = InStr(TESTDATA, "start-")
intEnd = InStr(TESTDATA, "-end")

Debug.Print Mid$(TESTDATA, intStart + Len("start-"), intEnd - intStart - Len("start-"))

Open in new window

0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now