如果我有一个字符串变量:
String example = "Hello, I'm here";
我想在每个变量前面'
和"
变量中添加一个转义字符(即实际上不是转义字符),我该怎么做?
我在这里并没有声称优雅,但我认为它可以满足您的要求(如果我弄错了,请纠正我):
public static void main(String[] args)
{
String example = "Hello, I'm\" here";
example = example.replaceAll("'", "\\\\'");
example = example.replaceAll("\"", "\\\\\"");
System.out.println(example);
}
输出
Hello, I\'m\" here
对于其他在这里寻求更通用的转义解决方案的人,在 Apache Commons Text 库上构建,您可以构建自己的转义器。看看StringEscapeUtils的例子:
import org.apache.commons.text.translate.AggregateTranslator;
import org.apache.commons.text.translate.CharSequenceTranslator;
import org.apache.commons.text.translate.LookupTranslator;
public class CustomEscaper {
private static final CharSequenceTranslator ESCAPE_CUSTOM;
static {
final Map<CharSequence, CharSequence> escapeCustomMap = new HashMap<>();
escapeCustomMap.put("+" ,"\\+" );
escapeCustomMap.put("-" ,"\\-" );
...
escapeCustomMap.put("\\", "\\\\");
ESCAPE_CUSTOM = new AggregateTranslator(new LookupTranslator(escapeCustomMap));
}
public static final String customEscape(final String input) {
return ESCAPE_CUSTOM.translate(input);
}
}
试试Apache Commons 文本库 -
System.out.println(StringEscapeUtils.escapeCsv("a\","));
System.out.println(StringEscapeUtils.escapeJson("a\","));
System.out.println(StringEscapeUtils.escapeEcmaScript("Hello, I'm \"here"));
结果:
"a"","
a\",
Hello, I\'m \"here