如何将转义字符添加到Java字符串?

时间:2021-04-15 22:25:58

If I had a string variable:

如果我有一个字符串变量:

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

and I wanted to add an escape character in front of every ' and " within the variable (i.e. not actually escape the characters), how would I do that?

我想在变量中的每个'和'前面添加一个转义字符(即实际上没有转义字符),我该怎么做?

1 个解决方案

#1


I'm not claiming elegance here, but i think it does what you want it to do (please correct me if I'm mistaken):

我不是在这里声称优雅,但我认为它可以做你想做的事(如果我弄错了,请纠正我):

public static void main(String[] args){    String example = "Hello, I'm\" here";    example = example.replaceAll("'", "\\\\'");    example = example.replaceAll("\"", "\\\\\"");    System.out.println(example);}

outputs

Hello, I\'m\" here

#1


I'm not claiming elegance here, but i think it does what you want it to do (please correct me if I'm mistaken):

我不是在这里声称优雅,但我认为它可以做你想做的事(如果我弄错了,请纠正我):

public static void main(String[] args){    String example = "Hello, I'm\" here";    example = example.replaceAll("'", "\\\\'");    example = example.replaceAll("\"", "\\\\\"");    System.out.println(example);}

outputs

Hello, I\'m\" here