0

設定に応じて、文字列の行末を変更しようとしています。基本的に私は文字列を持っていますが、ほとんどがLFで終わることはめったにありませんが、それは起こります。要求された場合はCRLFまたはCRに変更するか、要求された場合は純粋にLFであることを確認したいと思います。ソースとターゲットのプラットフォームはオペレーティングシステムによって異なるため、必要に応じて行末を変更したいと思います。

現在、私はこのコードでそれをやっています

    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");}

このコードが壊れやすいか、正規表現で何かを見逃しているのではないかと少し心配しているので、これを行うためのネイティブな方法があるのではないかと思っていました。それはJava 6であり、その場合はApacheStringUtilsを使用しています。役立つかもしれません。

ご入力いただきありがとうございます。

4

1 に答える 1

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");
}
于 2013-02-18T09:19:54.123 に答える