LBPLC
LBPLC

Reputation: 1571

Visual Basic Replacing Part Of A Text File

Referencing this answer to a very similar question I'm wondering how I can expand this code to act as searching for a place holder and modifying the text after it:

Dim fileReader As String = My.Computer.FileSystem.ReadAllText("C:\test.txt").Replace("Number Remaining: [oldvalue]", "Number Remaining: [newvalue]")
My.Computer.FileSystem.WriteAllText("C:\test2.txt", fileReader, False)

Where oldvalue is the number remaining before the edit (which I don't always know, so can't include it in the search) and newvalue is a value that is calculated elsewhere in the code.

The values are both Double types.

Any help would be appreciated.

Upvotes: 0

Views: 1020

Answers (1)

Blorgbeard
Blorgbeard

Reputation: 103437

You can use a simple regular expression to match a simple number.

First, add System.Text.RegularExpressions to your imports at the top of the file.

Imports System.Text.RegularExpressions

Then you can use something like this:

Dim newValue As Double = 12.34 'or whatever
Dim fileText As String = My.Computer.FileSystem.ReadAllText("C:\test.txt")
fileText = Regex.Replace(fileText,
                         "Number Remaining: [0-9]+(\.[0-9]+)?", 
                         string.Format("Number Remaining: {0}", newValue))
My.Computer.FileSystem.WriteAllText("C:\test2.txt", fileText, False)

The regex [0-9]+(\.[0-9]+)? means a digit ([0-9]), 1 or more times (+), optionally (?) followed by a dot (\.) and more digits.

If your number might be formatted differently, you will have to adjust the regex to suit.

Upvotes: 1

Related Questions