Search code examples
javacross-platformeol

Changing EOL in String based on setting


I'm trying to change the line endings of a String, depending on a setting. Basically I have Strings, mostly with LF endings, rarely something else but it happens, and I would like to be able to change them to CRLF or CR if asked, or make sure they are purely LF if that is asked. The source and target platform varies between operating systems, so I would like to change the line endings as I prefer.

Currently I'm doing it with this code

    if(this.eolCharacter.equalsIgnoreCase("CR")){
            //replaces all \r\n with \r
            //replaces all \n that are not preceded by \r with \r
            return input.replaceAll("\\r\\n", "\r").replaceAll("\\n", "\r");
    }else if(this.eolCharacter.equalsIgnoreCase("LF")){
            //replaces all \r\n with \n
            //replaces all \r with \n
            return input.replaceAll("\\r\\n", "\n").replaceAll("\\r", "\n");
    }else{
            //replaces all \n that are not preceded by \r
            //replaces all \r that are not followed by \n
            return input.replaceAll("(?<!\\r)\\n", "\r\n").replaceAll("\\r(?!\\n)", "\r\n");}

I'm a bit worried that this code might be to fragile or I missed something in the regular expressions, so I was wondering if there might be a native way to do this, it's Java 6, we're using the Apache StringUtils if that might help.

Thanks for any input!


Solution

  • Looks like it will work, but as EJP mentioned, you shouldn't need to do it, and it can be simplified as follows:

    if(this.eolCharacter.equalsIgnoreCase("CR")){
       return input.replaceAll("(\\r)?\\n", "\r");
    }else if(this.eolCharacter.equalsIgnoreCase("LF")){
       return input.replaceAll("\\r(\\n)?", "\n");
    }else{
       return input.replaceAll("((\\r)?\\n)|(\\r(?!\\n))", "\r\n");
    }