Sunday, August 4, 2013

Regular Expression to Replace Specific character between 2 immediate letters or numbers?

I'll gave it another try. This is my example text:



"Daft Punk, is great", "yes! they are, great"
"A B C D, E F G", "A B C D,E F G", "ABCD, EFG"

And here is my resulting text:



"Daft Punk - is great", "yes! they are - great"
"A B C D - E F G", "A B C D - E F G", "ABCD - EFG"

But, as often with Regex, if your text is irreguar the 'regular' expression won't help. Here comes my code snippet:



static void Main(string[] args) {
string path = <pathOfYourCSV>;
string destPath = <destPath>;
var lines = File.ReadLines(path);
string pattern = @"(?<=.+),\s?(?=.+)";
string replacement = @" - ";
string[] sep = new string[] {"\",", "\", "};
FileStream fs = File.Open(destPath, FileMode.Append);
StreamWriter sw = new StreamWriter(fs);
foreach (var item in lines) {
string[] linesArr = item.Split(sep, StringSplitOptions.RemoveEmptyEntries);
string[] arr = new string[linesArr.Length];
int cnt = 0;
foreach (var i in linesArr) {
if (String.IsNullOrEmpty(i)) break;
Match match = Regex.Match(i, pattern);
arr[cnt] = Regex.Replace(i, match.ToString(), replacement);
cnt++;
}
Console.WriteLine(String.Join(",", arr).Replace(",", "\","));
sw.WriteLine(String.Join(",", arr).Replace(",", "\","));
}
sw.Close();
fs.Close();
Console.ReadKey();
}



No comments:

Post a Comment