Java tutorial
//package com.java2s; public class Main { public static String replaceSpecialCharacters(String value) { if (value == null) return value; //only replace & if it not already an escaped sequence char[] val = value.toCharArray(); int pos = 0; while (pos < val.length) { if (val[pos] == '&') { int ampPos = pos; //move over until last non-whitespace character to see if ; while (pos < val.length && (val[pos] + "").matches("[^\\s]") && pos < ampPos + 5) { pos++; } if (val[pos] != ';') { pos = pos + 3; String newValue = value.substring(0, ampPos) + "&"; if (val.length > pos + 1) { newValue += value.substring(ampPos + 1); } value = newValue; val = value.toCharArray(); } } pos++; } value = value.replace("<", "<"); value = value.replace(">", ">"); value = value.replace("\"", """); value = value.replace("'", "'"); return value; } }