正则表达式替换Windows换行符

时间:2015-06-05 14:22:44

标签: c# regex

我有一些代码,它应该用空字符替换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()

1 个答案:

答案 0 :(得分:3)

您使用的是逐字字符串文字,因此\\被视为文字\。 因此,您的正则表达式实际上与\rn匹配。 使用

locationString = Regex.Replace(locationString, @"[\r\n]+", "");

[\r\n]+模式将确保您删除每个\r\n符号,如果您的新行字符混合使用,则无需担心文件。 (有时,我在文本文件中有\n\r\n个结尾。)