chanjianyi
chanjianyi

Reputation: 615

How to make replaceAll working in java?

I've tried different way but not working yet.

public String SuEscapeHTML(String text){
    text=text.replaceAll("/&/g", "&");
    // and how to deal with the double quote? text=text.replaceAll("/"/g", """);
    text=text.replaceAll("/'/g", "'");
    text=text.replaceAll("/</g", "&lt;");
    text=text.replaceAll("/>/g", "&gt;");
    text=text.replaceAll("/\\/g", "&#92;");
    System.out.println(text);
    return text;
}

nothing change by using this function.

So How to make it working?

Upvotes: 0

Views: 363

Answers (1)

rock321987
rock321987

Reputation: 11032

The syntax of regex you are using is of JavaScript. This is how you will do it in Java

String text = "&>\"<\\'"; //You need to escape " in text also

System.out.println(text.replaceAll("&", "&amp;")); 
System.out.println(text.replaceAll("\"", "&quot;")); //For quotes
System.out.println(text.replaceAll("'", "&apos;"));
System.out.println(text.replaceAll("<", "&lt;"));
System.out.println(text.replaceAll(">", "&gt;"));
System.out.println(text.replaceAll("\\\\", "&#92;"));

Ideone Demo

Upvotes: 2

Related Questions