实时搜索和替换 [英] Realtime Search and Replace

查看:48
本文介绍了实时搜索和替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含大量数字的文件,我想减少这些数字以构建一个新文件.首先,我使用 File.ReadAllText 提取所有文本,然后从包含以逗号或空格分隔的数字的每一行中拆分并提取数字.扫描后,我用新的减少的数字替换每个找到的数字的所有出现,但问题是这种方法容易出错,因为有些数字被替换多次

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?

谢谢.

推荐答案

我认为正则表达式可以在这里提供帮助

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);

这篇关于实时搜索和替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆