Java – use wildcards to search in the string collection

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 the map has "test", "best", "crest", "zest", "testy", "tether", "temp", "teat", "Tempest" The query for te * t should return "teat", "Tempest", "test" For 'test *', it should return "test", "testy" How? Are there any wildcard search strings? I cannot use any external libraries

Solution

String queryStr="te*t";
String queryStr="te*t";

queryStr = queryStr.replaceAll("\\*","\\\\w*");

System.out.println(query(queryStr));

Complete plan

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 content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>