How can I add escape characters to a Java String?

后端 未结 3 721
梦谈多话
梦谈多话 2020-12-11 01:19

If I had a string variable:

String example = \"Hello, I\'m here\";

and I wanted to add an escape character in front of every \'

3条回答
  •  北海茫月
    2020-12-11 02:01

    Try Apache Commons Text library-

        System.out.println(StringEscapeUtils.escapeCsv("a\","));
        System.out.println(StringEscapeUtils.escapeJson("a\","));
        System.out.println(StringEscapeUtils.escapeEcmaScript("Hello, I'm \"here"));
    

    Result:

    "a"","
    a\",
    Hello, I\'m \"here
    

提交回复
热议问题