Java tutorial
//package com.java2s; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { private static final Pattern gt = Pattern.compile(">"); private static final Pattern lt = Pattern.compile("<"); private static final Pattern quot = Pattern.compile("\""); private static final Pattern amp = Pattern.compile("&"); public static String encode(String str) { if (str == null) { return null; } Matcher gtMatcher = gt.matcher(str); if (gtMatcher.matches()) { str = gtMatcher.replaceAll(">"); } Matcher ltMatcher = lt.matcher(str); if (ltMatcher.matches()) { str = ltMatcher.replaceAll("<"); } Matcher quotMatcher = quot.matcher(str); if (quotMatcher.matches()) { str = quotMatcher.replaceAll("""); } Matcher ampMatcher = amp.matcher(str); if (ampMatcher.matches()) { str = ampMatcher.replaceAll("&"); } return str; } }