Click here to Skip to main content
11,803,019 members (77,952 online)
Rate this: bad
Please Sign up or sign in to vote.
See more: VB VB10.0 string VB.NET
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 at 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 at 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
0 OriginalGriff 335
1 KrunalRohit 291
2 F-ES Sitecore 270
3 CPallini 270
4 Sergey Alexandrovich Kryukov 234
0 OriginalGriff 2,950
1 Maciej Los 1,910
2 KrunalRohit 1,862
3 CPallini 1,735
4 Richard MacCutchan 1,157

Advertise | Privacy | Mobile
Web04 | 2.8.151002.1 | Last Updated 20 May 2012
Copyright © CodeProject, 1999-2015
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