You are viewing a plain text version of this content. The canonical link for it is here.
Posted to general@jakarta.apache.org by Apache Wiki <wi...@apache.org> on 2005/03/31 00:06:47 UTC

[Jakarta Wiki] Update of "RegexpKeyedMap" by ManikSurtani

Dear Wiki user,

You have subscribed to a wiki page or wiki category on "Jakarta Wiki" for change notification.

The following page has been changed by ManikSurtani:
http://wiki.apache.org/jakarta/RegexpKeyedMap

New page:
A map that uses a regular expression as a key.

'''Purpose:''' To create a Java Map that allowed me to pass in any arbitrary String as a key to it's get() method, and for the Map implementation to attempt to match this key against various regexp-keys it would store, and return any matching value (or null if nothing matches)

'''Dependencies:''' This class relies on v1.3 of Jakarta's Regexp package

'''Examples:''' Ok, that explanation above was rubbish.  Nothing works quite as well as an example.  Here we go:

{{{

RegexpKeyedMap map = new RegexpKeyedMap();
map.put( "^Green.*$", "Your sentence starts with Green" );
map.put( "^Blue.*$", "Your sentence starts with Blue" );
map.put( "Orange", "Your sentence contains the word Orange" );


// contains some stuff typed in my the user
String sentence = "Green apples happen to be my favourite";

// responseText will be "Your sentence starts with Green"
String responseText = map.get( sentence );

sentence = "I like green apples a lot";

// responseText will be null since nothing matched
responseText = map.get( sentence ); 


sentence = "Green apples and Oranges are both quite good";

// responseText will be indeterminate - it could be either of "Your sentence starts with Green" 
// or "Your sentence contains the word Orange" - this is because the RegexpKeyedMap uses a HashMap
// to store its contents and ordering of elements is not guaranteed.  The first match is returned.
responseText = map.get( sentence );

}}}

'''Download:''' here... 

'''Author:''' Manik Surtani (manik at surtani dot org)