Realtime Search and Replace

I have a file which contains lots of numbers which I want to reduce to construct a new file. First, I extract all the text using File.ReadAllText, then I split and extract numbers from each line that contains a number which are separated by commas or spaces. After scan, I replace all occurrences of each found number with the new reduced number but the problem is that this method is error prone since some numbers get replaced more than once

Here's the code I'm using:

List<float> oPaths = new List<float>();
List<float> nPaths = new List<float>();
var far = File.ReadAllText("paths.js");
foreach(var s in far.Split('\n'))
{
    //if it starts with this that means there are some numbers
    if (s.StartsWith("\t\tpath:"))
    {
        var paths = s.Substring(10).Split(new[]{',', ' '});
        foreach(var n in paths)
        {
            float di;
            if(float.TryParse(n, out di))
            {
                if(oPaths.Contains(di)) break;
                oPaths.Add(di);
                nPaths.Add(di * 3/4);
            }
        }
    }
}

//second iteration to replace old numbers with new ones
var ns = far;
    for (int i = 0; i < oPaths.Count; i++)
    {
        var od = oPaths[i].ToString();
        var nd = nPaths[i].ToString();
        ns = ns.Replace(od, nd);
    }
    File.WriteAllText("npaths.js", ns);

As you can see, the above method is redundant as it does not replace the strings on real time. Maybe my head is full, but I'm just lost on how to go about this. Any ideas?

Thanks.

Answers


I think a regex can help here

string text = File.ReadAllText(file);
string newtext = Regex.Replace(text, @"\b(([0-9]+)?\.)?[0-9]+\b", m =>
    {
        float f;
        if (float.TryParse(m.Value, NumberStyles.Float, CultureInfo.InvariantCulture, out f)) f *= 3.0f / 4;
        return f.ToString();
    });
File.WriteAllText(file, newtext);

Need Your Help

Compare SortedDictionary<string, List<foo>> C#

c# linq

I asked similar question here , I am wondering how you can achieve same result with LINQ

SSL config on Apache

openssl opensuse apache2.2

I have a basic understanding on both apache2 and ssl and yes let's throw zabbix, the project that I'm working on, so please forgive me.