Here you can find the source of substituteTokens(String pattern, Map tokens)
public static String substituteTokens(String pattern, Map tokens)
//package com.java2s; /*//from w w w .j a v a 2s . c o m * This file is subject to the license found in LICENCE.TXT in the root directory of the project. * * version 1.4 */ import java.util.Map; public class Main { public static String substituteTokens(String pattern, Map tokens) { StringBuffer buffer = new StringBuffer(); char[] chars = pattern.toCharArray(); StringBuffer optionalPart = null; StringBuffer tokenBuffer = null; boolean insideOptionalPart = false; boolean insideToken = false; boolean tokenHadValue = false; for (int i = 0; i < chars.length; i++) { switch (chars[i]) { case '(': if (insideOptionalPart) { throw new IllegalArgumentException( "invalid start of optional part at position " + i + " in pattern " + pattern); } optionalPart = new StringBuffer(); insideOptionalPart = true; tokenHadValue = false; break; case ')': if (!insideOptionalPart || insideToken) { throw new IllegalArgumentException( "invalid end of optional part at position " + i + " in pattern " + pattern); } if (tokenHadValue) { buffer.append(optionalPart.toString()); } insideOptionalPart = false; break; case '[': if (insideToken) { throw new IllegalArgumentException( "invalid start of token at position " + i + " in pattern " + pattern); } tokenBuffer = new StringBuffer(); insideToken = true; break; case ']': if (!insideToken) { throw new IllegalArgumentException( "invalid end of token at position " + i + " in pattern " + pattern); } String token = tokenBuffer.toString(); Object tokenValue = tokens.get(token); String value = (tokenValue == null) ? null : tokenValue.toString(); if (insideOptionalPart) { tokenHadValue = (value != null) && (value.length() > 0); optionalPart.append(value); } else { if (value == null) { // the token wasn't set, it's kept as is value = "[" + token + "]"; } buffer.append(value); } insideToken = false; break; default: if (insideToken) { tokenBuffer.append(chars[i]); } else if (insideOptionalPart) { optionalPart.append(chars[i]); } else { buffer.append(chars[i]); } break; } } if (insideToken) { throw new IllegalArgumentException("last token hasn't been closed in pattern " + pattern); } if (insideOptionalPart) { throw new IllegalArgumentException("optional part hasn't been closed in pattern " + pattern); } return buffer.toString(); } }