Sunday, 15 September 2013

java - Changing EOL in String based on setting -



java - Changing EOL in String based on setting -

i'm trying alter line endings of string, depending on setting. have strings, lf endings, else happens, , able alter them crlf or cr if asked, or create sure purely lf if asked. source , target platform varies between operating systems, alter line endings prefer.

currently i'm doing code

if(this.eolcharacter.equalsignorecase("cr")){ //replaces \r\n \r //replaces \n not preceded \r \r homecoming input.replaceall("\\r\\n", "\r").replaceall("\\n", "\r"); }else if(this.eolcharacter.equalsignorecase("lf")){ //replaces \r\n \n //replaces \r \n homecoming input.replaceall("\\r\\n", "\n").replaceall("\\r", "\n"); }else{ //replaces \n not preceded \r //replaces \r not followed \n homecoming input.replaceall("(?<!\\r)\\n", "\r\n").replaceall("\\r(?!\\n)", "\r\n");}

i'm bit worried code might fragile or missed in regular expressions, wondering if there might native way this, it's java 6, we're using apache stringutils if might help.

thanks input!

looks work, ejp mentioned, shouldn't need it, , can simplified follows:

if(this.eolcharacter.equalsignorecase("cr")){ homecoming input.replaceall("(\\r)?\\n", "\r"); }else if(this.eolcharacter.equalsignorecase("lf")){ homecoming input.replaceall("\\r(\\n)?", "\n"); }else{ homecoming input.replaceall("((\\r)?\\n)|(\\r(?!\\n))", "\r\n"); }

java cross-platform eol

No comments:

Post a Comment