Regex替换Windows换行符

本文关键字:换行符 Windows 替换 Regex | 更新日期: 2023-09-27 17:53:32

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

Regex替换Windows换行符

您正在使用逐字字符串字面值,因此''被视为字面值'。因此,您的正则表达式实际上匹配', rn。使用

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

['r'n]+模式将确保您将删除每个'r'n符号,并且您不必担心是否在文件中混合了换行字符。(有时,我在文本文件中同时使用'n'r'n结尾)。