Sunday, August 4, 2013

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



Hello my friend:


I am writing a Text file to CSV Script but I want to remove all embedded commas, meaning commas between words or letters:


For example: I want to change this: "Daft Punk, is great" to "Daft Punk - is great"
So if my text file looks like this: "Daft Punk, is great", "yes! they are, great"

Then the result will look like this:
"Daft Punk - is great", "yes! they are - great"


I do not know much about Regex. But is there a Regex that I can add to my code below to replace any comma that is between two letters?



More Examples:



"A B C D, E F G" or "A B C D,E F G" would turn to this: "A B C D - E F G"


Here is my code:




static void TextToCSV(string s, TextWriter writer)
{
foreach (var line in s.Replace(", ", "").Split(new string[] { Environment.NewLine}, StringSplitOptions.None))
{
foreach (var t in line)
{
writer.Write(t);
}
writer.WriteLine();
}
writer.Flush();
}

static void Main(string[] args)
{
TextReader reader = new StreamReader(@"C:\myfolder\sample.txt");
string a = reader.ReadToEnd();
reader.Close();

FileStream aFile = new FileStream(@"C:\myfolder\sample.csv", FileMode.Create);

TextToCSV(a, new StreamWriter(aFile));
aFile.Close();
}



Thanks everyone!






No comments:

Post a Comment