Find and replace all NewLine or BreakLine characters with \n in a String - Platform independent

后端 未结 3 1665
深忆病人
深忆病人 2020-12-09 19:58

I am looking for a proper and robust way to find and replace all newline or breakline chars from a String independent of any OS platfo

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-09 20:01

    This seems to work well:

    String s = "This is a String\nand all newline chars\nshould be replaced in this example.";
    System.out.println(s);
    System.out.println(s.replaceAll("[\\n\\r]+", "\\\\n"));
    

    By the way, you don't need to catch exception.

提交回复
热议问题