简体   繁体   中英

Replacing multiple header name using regex

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.

I'm not really 'into' C#, but it looks to me that you need to:

  • remove the backslash left of the asteriks in the regexes
  • replace header with newHeader in the second and third Replace actions.

Also, the square brackets around \\w are not necessary since you are not testing for 'any of the following characters'

Your code could then be like:

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM