[英]How can I add escape characters to a Java String?
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 (ie not actually escape the characters), how would I do that?我想在变量中的每个
'
和"
前面添加一个转义字符(即实际上不转义字符),我该怎么做?
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
For others who get here for a more general escaping solution, building on Apache Commons Text library you can build your own escaper.对于来到这里寻求更通用转义解决方案的其他人,在 Apache Commons Text 库上构建您可以构建自己的转义器。 Have a look at StringEscapeUtils for examples:
看看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);
}
}
Try Apache Commons Text library-尝试Apache Commons 文本库-
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.