Reputation: 570
I have this bit of code, which is supposed to replace the Windows linebreak character (\r\n
) with an empty character.
However, it does not seem to replace anything, as if I view the string after the regex expression is applied to it, the linebreak characters are still there.
private void SetLocationsAddressOrGPSLocation(Location location, string locationString)
{
//Regex check for the characters a-z|A-Z.
//Remove any \r\n characters (Windows Newline characters)
locationString = Regex.Replace(locationString, @"[\\r\\n]", "");
int test = Regex.Matches(locationString, @"[\\r\\n]").Count; //Curiously, this outputs 0
int characterCount = Regex.Matches(locationString,@"[a-zA-Z]").Count;
//If there were characters, set the location's address to the locationString
if (characterCount > 0)
{
location.address = locationString;
}
//Otherwise, set the location's coordinates to the locationString.
else
{
location.coordinates = locationString;
}
} //End void SetLocationsAddressOrGPSLocation()
Upvotes: 1
Views: 224
Reputation: 627469
You are using verbatim string literal, thus \\
is treated as a literal \
.
So, your regex is actually matching \
, r
and n
.
Use
locationString = Regex.Replace(locationString, @"[\r\n]+", "");
This [\r\n]+
pattern will make sure you will remove each and every \r
and \n
symbol, and you won't have to worry if you have a mix of newline characters in your file. (Sometimes, I have both \n
and \r\n
endings in text files).
Upvotes: 3