Search with wildcard in a Collection of String

Multi tool use
Search with wildcard in a Collection of String
I have a HashMap<Integer,String>
. I tried the following code to query the Map and return all possible values
HashMap<Integer,String>
public Collection<String> query(String queryStr) {
List<String> list = new ArrayList<String>();
for (Map.Entry<String, Integer> entry : myMap.entrySet()) {
if (queryStr.matches(entry.getKey()))
list.add(entry.getKey());
}
if (list.isEmpty())
return null;
else
return list;
}
If map has "test","best","crest","zest","testy","tether","temper","teat","tempest"
. A query of te*t
should return "teat","tempest","test"
. For 'test*' it should return "test", "testy". How to implement it? Is there any wildcard search for string? And I can't use any external libraries.
"test","best","crest","zest","testy","tether","temper","teat","tempest"
te*t
"teat","tempest","test"
String
matches
Pattern
Matcher
Why return null if the list is empty? It would make more sense to just return an empty list.
– arshajii
Oct 1 '13 at 2:55
A test of assertArrayEquals(new Object {"best","crest","tempest","test","zest"}, getSortedArray(dict.query("*est"))); is not returning anything.
– NEO
Oct 1 '13 at 2:55
@arshajii Its the requirement of the test cases. I cannot change them.
– NEO
Oct 1 '13 at 2:56
2 Answers
2
String queryStr="te*t";
queryStr = queryStr.replaceAll("*", "\w*");
System.out.println(query(queryStr));
The Complete program
public class sample {
static List<String> values = Arrays.asList("test","best","crest","zest","testy","tether","temper","teat","tempest");
/**
* @param args
*/
public static void main(String args) {
String queryStr = "te*t";
queryStr = queryStr.replaceAll("*", "\w*");
System.out.println(queryStr);
System.out.println(query(queryStr));
}
public static Collection<String> query(String queryStr) {
List<String> list = new ArrayList<String>();
for (String str : values) {
if (str.matches(queryStr))
list.add(str);
}
if (list.isEmpty())
return null;
else
return list;
}
}
The matcher w*
searches for the following chars only : [a-zA-Z_0-9]
If you would like to search for all the chars using the *
matcher then you should try this:
w*
[a-zA-Z_0-9]
*
queryStr = queryStr.replaceAll("*", ".*");
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
String
has the methodmatches
. You can also usePattern
andMatcher
classes.– Sotirios Delimanolis
Oct 1 '13 at 2:52