【发布时间】:2019-04-15 00:28:58
【问题描述】:
我目前正在制作一个可以读取 csv 文件并可以使用 Regex 和 csvhelper 替换标题名称的项目。
我有很多 csv 文件,有时它们有不同的标题名称。这些是我的示例 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
如何将标题名称更改为正确的标题名称?像这样:
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;
}
在此代码中,正则表达式仅替换第一个匹配项。
我知道使用映射是可能的,但它需要手动放置可能的标题名称。我想要的是动态替换标题。
【问题讨论】:
标签: c# regex replace csvhelper