我有一些代码,它应该用空字符替换Windows换行符(\r\n
)。
但是,它似乎没有替换任何东西,就好像我在应用正则表达式后查看字符串一样,换行符仍然存在。
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()
答案 0 :(得分:3)
您使用的是逐字字符串文字,因此\\
被视为文字\
。
因此,您的正则表达式实际上与\
,r
和n
匹配。
使用
locationString = Regex.Replace(locationString, @"[\r\n]+", "");
此[\r\n]+
模式将确保您删除每个\r
和\n
符号,如果您的新行字符混合使用,则无需担心文件。 (有时,我在文本文件中有\n
和\r\n
个结尾。)