Click here to Skip to main content
15,886,799 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:

...
foobar=6000.0000
qwerty=200.0000
poopxyz=7000.0000
...

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
Comments
Shahan Ayyub 19-May-12 13:45pm    
can you provide a sample of your expected text after processing ?

The Replace method of System.Text.RegularExpressions.Regex class explained here http://msdn.microsoft.com/en-US/library/taz3ak2f%28v=vs.80%29[^] 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 http://regexhero.net/tester/[^].

To replace other combinations use variables for foobar and the replace string.
VB
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)
 
Share this answer
 
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:

foobar=.{1,}\.

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

So:

foobar=oldvalue.test

Would become

foobar=newvalue.test

Here is a link on beginning regex:

Regular Expressions Quick Start[^]
 
Share this answer
 
Comments
theraveman 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)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900