替换文本文件中的值只替换最后一个数字?

时间:2016-04-14 01:11:31

标签: c# writing

所以我试图在游戏配置(.txt)中编辑高度,当我这样做时,我只会替换最后一个数字。我认为这是因为价值是一个浮动。例如,[height = 0.11]但删除函数将采用int的?

在文本文件中:   身高= 0.11

一旦新高度被写入(0.2):   身高= 0.10.2

我目前的代码:

    string text = File.ReadAllText(carDataFile + "\\steamapps\\common\\Car Mechanic Simulator 2015\\cms2015_Data\\Datacars\\car_BoltHellcat.txt");
    const string Pattern = @"height= (?<Number>[\d\.])";
    Match match = Regex.Match(text, Pattern, RegexOptions.IgnoreCase);

    if (match.Success)
    {
        int index = match.Groups["Number"].Index;
        int length = match.Groups["Number"].Length;

        text = text.Remove(index, length);
        text = text.Insert(index, height.ToString());

        File.WriteAllText(carDataFile + "\\steamapps\\common\\Car Mechanic Simulator 2015\\cms2015_Data\\Datacars\\car_BoltHellcat.txt", text);
    }

1 个答案:

答案 0 :(得分:0)

我设法通过替换整个[height= 0.11]值而不是仅仅尝试替换最后一组数字来实现此目的。我认为问题在于试图确定哪个组具有正确的匹配和正确的索引/长度。

string text = "stuff before [height= 0.11] stuff after";
string height = "height= 0.2";
const string Pattern = @"height= (\d+(\.\d{1,2})?)";
Match match = Regex.Match(text, Pattern, RegexOptions.IgnoreCase);

if (match.Success)
{
    int index = match.Index;
    int length = match.Length;

    text = text.Remove(index, length);
    text = text.Insert(index, height.ToString());

    Console.WriteLine(text);
}

输出:

stuff before [height= 0.2] stuff after