How can I add escape characters to a Java String?

后端 未结 3 729
梦谈多话
梦谈多话 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 01:59

    For others who get here for a more general escaping solution, building on Apache Commons Text library you can build your own escaper. Have a look at StringEscapeUtils for examples:

    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 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);
        }
    }
    

提交回复
热议问题