0

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!

Markus
  • 295
  • 4
  • 12
  • 1
    Why? The various `readLine()` methods all cope correctly with all the known variants, and the current line terminator is available via a system property if you really need it. The whole idea is not to care. – user207421 Feb 18 '13 at 09:29
  • The problem is that the strings are written to text files, which are then needed in some low level programs and these sometimes can't cope with these, and we have had problems in the past unfortunately. – Markus Feb 18 '13 at 09:48

1 Answers1

2

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");
}
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138