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

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


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).

1 Solution
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
slightwv (䄆 Netminder) Commented:
I would look at regular expressions.

My straight VB is pretty rusty but check out:

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.
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)

Set fileStream = fso.OpenTextFile("c:\workshop\File1.txt", 2)
fileStream.Write (s)
End Sub
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


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