I'm currently making a project that can read a csv file and can replace the header name by the use of Regex and csvhelper.
I have lots of csv filse and sometimes they have different header names. These are my sample csv files:
example 1:
BranchName,Latitude,Longitude
China,89.2422,121.1312
example 2:
Name,Lat,Long
New Zealand,21.1212,110.3141
example 3:
B_Name4,Lati12,Longitude21
Australia,34.1231,143.1231
How can I change the header names into the correct header names? Like this:
Branch_Name,Latitude,Longitude China,89.2422,121.1312
So far my code is this:
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;
}
In this code the regex is only replacing the first match.
I know that it is possible by using mapping but it requires to manually putting the possible header names. What I want is to dynamically replace the header.