更改字符串 [] 文件中的字符串 = File.ReadAllLines(csspath);

Change string in string[] files = File.ReadAllLines(csspath);


我尝试更改从函数创建的 array 中的 string File.ReadAllLines(csspath).

我尝试做的是使用 Regex.Replace 将输出 分配给 string(在本例中为 file)我一起工作。

在函数中,我得到了数组和我想要将我的字符串更改为的字符串。

问题是,当我使用file.Replace(file, outp);时,我需要保存新数组,我想我不知道如何处理这个问题。

我应该如何处理这个解决方案?

我也想使用 Regex.Match 函数,但我得到的是匹配而不是替换。

private static void MyFunction(string[] files,string changeto)
{
    var outp = "";

    foreach (var file in files)
    {
        if (file.Contains("font-family"))
        {
            //var match = Regex.Match(file, "'.*';");

            outp = Regex.Replace(file, "'.*';", changeto);

            file.Replace(file, outp);
        }
    }
}

我建议设计更改:让方法return更改(而不是void):

private static IEnumerable<string> MyFuction(IEnumerable<string> lines, string changeTo) {
  return lines
    .Select(line => Regex.Replace(line, "'.*';", changeTo)); 
}

所以你可以这样使用它:

// 1. Read lines from the file
// 2. Make required changes
// 3. Organize the final result as an array
string[] data = MyFuction(File.ReadLines(csspath))
  .ToArray();

或者您甚至可以完全摆脱该方法并获得可读代码:

string[] data = File
  .ReadLines(csspath)                                     // read file
  .Select(line => Regex.Replace(line, "'.*';", changeTo)) // make changes
  .ToArray();                                             // materialize as an array