使用正则表达式替换多个 header 名称

Replacing multiple header name using regex

我目前正在制作一个可以读取 csv 文件并可以使用 Regex 和 csvhelper 替换 header 名称的项目。

我有很多 csv 文件,有时它们有不同的 header 名称。这些是我的示例 csv 文件:

示例 1:

BranchName,Latitude,Longitude
China,89.2422,121.1312

示例 2:

Name,Lat,Long
New Zealand,21.1212,110.3141

示例 3:

B_Name4,Lati12,Longitude21
Australia,34.1231,143.1231

如何将 header 名称更改为正确的 header 名称?像这样:

Branch_Name,Latitude,Longitude
China,89.2422,121.1312

到目前为止我的代码是这样的:

csv.Reader.Configuration.PrepareHeaderForMatch = header =>
{
var newHeader = Regex.Replace(header, "@([\w]\*name[\w]*)", "Branch_Name", RegexOptions.IgnoreCase);
newHeader = Regex.Replace(header, "@([\w]\*lat[\w]*)", "Latitude", RegexOptions.IgnoreCase);
newHeader = Regex.Replace(header, "@([\w]\*long[\w]*)", "Longitude", RegexOptions.IgnoreCase);

return newHeader;
}

在此代码中,正则表达式仅替换第一个匹配项。
我知道使用映射是可能的,但它需要手动输入可能的 header 名称。我想要的是动态替换 header.

我不是真正的 'into' C#,但在我看来您需要:

  • 删除正则表达式中星号左侧的反斜杠
  • 在第二个和第三个替换操作中将 header 替换为 newHeader

此外,\w 周围的方括号不是必需的,因为您没有测试 'any of the following characters'

你的代码可以是这样的:

csv.Reader.Configuration.PrepareHeaderForMatch = header =>
{
    var newHeader = Regex.Replace(header, @"(\w*Name\w*)", "Branch_Name", RegexOptions.IgnoreCase);
    newHeader = Regex.Replace(newHeader, @"(\w*Lat\w*)", "Latitude", RegexOptions.IgnoreCase);
    return Regex.Replace(newHeader, @"(\w*Long\w*)", "Longitude", RegexOptions.IgnoreCase);
}