实时搜索和替换(Realtime Search and Replace)

2019-10-30 03:42发布

我有一个包含很多,我想,以减少建造一个新的文件编号的文件。 首先,我使用提取所有文本File.ReadAllText ,然后我分裂和提取号码从包含其通过逗号或空格分隔的数的每一行。 扫描结束后,我替换每个数发现​​所有出现的新的数量减少,但问题是,这种方法很容易出错,因为一些数字被替换不止一次

下面是我使用的代码:

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

正如你所看到的,上面的方法是多余的,因为它不会取代实时字符串。 也许我的头是满的,但我只是失去了对如何去这一点。 有任何想法吗?

谢谢。

Answer 1:

我认为,正则表达式可以帮助这里

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


Answer 2:

Just after typing the question I realized the answer was to iterate character by character and replace accordingly. Here's the code I used to get this to work:

string nfar = "";
var far = File.ReadAllText("paths.js");
bool neg = false;
string ccc = "";
for(int i = 0; i < far.Length; i++)
{
    char c = far[i];
    if (Char.IsDigit(c) || c == '.')
    {
        ccc += c;
        if (far[i + 1] == ' ' || far[i + 1] == ',')
        {
            ccc = neg ? "-" + ccc : ccc;
            float di;
            if (float.TryParse(ccc, out di))
            {
                nfar += (di*0.75f).ToString();
                ccc = "";
                neg = false;
            }
        }
    }
    else if (c == '-')
    {
        neg = true;
    }
    else
    {
        nfar += c;
    }
}
File.WriteAllText("nfile.js", nfar);

Comments and/or optimization suggestions are welcome.



文章来源: Realtime Search and Replace