Re: Java search and replace?
"bugnthecode" <bugnthecode@gmail.com> writes:
Hello $user, my name is $name.
public class Main
{
public static java.lang.String replace
( final java.lang.String template,
final java.util.Map<java.lang.String,java.lang.String> map )
{ final java.lang.StringBuilder list =
new java.lang.StringBuilder( "\\$(" );
for( final java.lang.String key: map.keySet() )
{ list.append( key ); list.append( "|" ); }
list.append( "[^\\s\\S])" );
java.util.regex.Pattern pattern =
java.util.regex.Pattern.compile( list.toString() );
java.util.regex.Matcher matcher = pattern.matcher( template );
final java.lang.StringBuffer stringBuffer = new java.lang.StringBuffer();
while( matcher.find() )
{ final java.lang.String string = matcher.group( 1 );
matcher.appendReplacement
( stringBuffer, map.get( string )); }
matcher.appendTail( stringBuffer );
return stringBuffer.toString(); }
public static void main( final java.lang.String[] args )
{ final java.util.Map<java.lang.String,java.lang.String> map =
new java.util.HashMap<java.lang.String,java.lang.String>();
map.put( "user", "Mary" );
map.put( "name", "Patricia" );
java.lang.System.out.println
( replace( "Hello $user, my name is $name.", map ) ); }}
Hello Mary, my name is Patricia.