Click here to Skip to main content
13,086,120 members (85,144 online)
Rate this:
Please Sign up or sign in to vote.
I can't figure out how to find a phrase in a text file, and replace it with something else. Tried lots of things but always ending up with empty hands.

Suppose there's a text file in this order:


I want to;
1) Find the phrase (e.g. foobar) by scanning the whole text,

2) Replace the number coming after "=" and before ".", namely "6000" in the middle with any number value i want.

I don't need the parts before "=" and after ".", only the number in the middle.

I'd be more than glad if anybody can assist me to or give me the code that can do this task. Thanks in advance

Platform: VB10 / .net 4.0
Posted 19-May-12 7:03am
Shahan Ayyub 19-May-12 13:45pm
can you provide a sample of your expected text after processing ?
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

The Replace method of System.Text.RegularExpressions.Regex class explained here[^] can be used for this purpose using the pattern (?<=foobar\s*=\s*)([^=.]+)(?=\s*\.) which matches a word if it is preceded by foobar= and followed by . even when there is white space between foobar & =, = & the required word, required word & . This pattern can be tested here[^].

To replace other combinations use variables for foobar and the replace string.
Dim fileText as String = System.IO.File.ReadAllText(fileName)
Dim modifiedText as String = System.Text.RegularExpressions.Regex.Replace( _
    fileText,"(?<=foobar\s*=\s*)([^=.]+)(?=\s*\.)","5000", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

This sounds like a job for regex (Regular Expressions)!

Doing a regex replace will allow you to do this as it supports quite complex wild card structures.

A regex string similar to this:


replace value would be.... foobar=newvalue.



Would become


Here is a link on beginning regex:

Regular Expressions Quick Start[^]
Çağan Çelik 19-May-12 15:08pm
Could you elaborate a little bit more? I find it very difficult to implement here.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web03 | 2.8.170813.1 | Last Updated 20 May 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100