Note that there are some explanatory texts on larger screens.

plurals
  1. POJava: Search in HashMap keys based on regex?
    text
    copied!<p>I'm building a thesaurus using a HashMap to store the synonyms. </p> <p>I'm trying to search through the words based on a regular expression: the method will have to take a string as parameter and return an array of results. Here's my first stab at it:</p> <pre><code>public ArrayList&lt;String&gt; searchDefinition(String regex) { ArrayList&lt;String&gt; results = new ArrayList&lt;String&gt;(); Pattern p = Pattern.compile(regex); Set&lt;String&gt; keys = thesaurus.keySet(); Iterator&lt;String&gt; ite = keys.iterator(); while (ite.hasNext()) { String candidate = ite.next(); Matcher m = p.matcher(candidate); System.out.println("Attempting to match: " + candidate + " to " + regex); if (m.matches()) { System.out.println("it matches"); results.add(candidate); } } if (results.isEmpty()) { return null; } else { return results; } } </code></pre> <p>Now, this does not work as I would expect (or maybe I'm using regular expressions incorrectly). If I have the following keys in the hashmap:</p> <pre><code>cat, car, chopper </code></pre> <p>then by calling <code>searchDefinition("c")</code> or <code>searchDefinition("c*")</code> I get <code>null</code>.</p> <ol> <li>How do I make this work as expected?</li> <li>Is there a better data structure than HashMap to keep a <code>graph</code> like needed by a thesaurus? (curiosity only, as for this assignment we're asked to use Java Collection Map).</li> <li>Anything else I'm doing innapropriately in the code above?</li> </ol> <p>Thanks, Dan</p> <p>EDIT: I've corrected the example. It doesn't work even if I use the correct case.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload