我有这段代码,应该用空字符替换 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()
请您参考如下方法:
您正在使用逐字字符串文字,因此 \\
被视为文字 \
。 因此,您的正则表达式实际上匹配 \
、r
和 n
。 使用
locationString = Regex.Replace(locationString, @"[\r\n]+", "");
此 [\r\n]+
模式将确保您将删除每个 \r
和 \n
符号,并且如果您的文件中混有换行符,您不必担心。 (有时,我在文本文件中同时使用 \n
和 \r\n
结尾)。