I have a HashMap<Integer,String>
. I tried the following code to query the Map and return all possible values
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.
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:
queryStr = queryStr.replaceAll("\\*", ".*");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.