Java tutorial
//package com.java2s; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static final String XML_ENTITY_NAMED_GROUP = "name"; public static final String XML_ENTITY_RE = "\\&(?<" + XML_ENTITY_NAMED_GROUP + ">[#\\w\\d]*?);"; /** * This function will return a map that contains entity names as keys, and random integer strings as values. The values are guaranteed not to have appeared * in the original xml. * * @param xml * The xml to generate the replacements for * @return a map of entity names to unique random strings */ private static Map<String, String> calculateEntityReplacements(final String xml) { final Map<String, String> retValue = new HashMap<String, String>(); final Random randomGenerator = new Random(); /* compile the regular expression */ final Pattern injectionSequencePattern = Pattern.compile(XML_ENTITY_RE); /* find any matches */ final Matcher injectionSequencematcher = injectionSequencePattern.matcher(xml); /* loop over the regular expression matches */ while (injectionSequencematcher.find()) { final String entityName = injectionSequencematcher.group(XML_ENTITY_NAMED_GROUP); if (!retValue.containsKey(entityName)) { String randomReplacement; do { randomReplacement = "[" + randomGenerator.nextInt() + "]"; } while (xml.indexOf(randomReplacement) != -1); retValue.put(entityName, randomReplacement); } } return retValue; } }