在字符串集合中使用通配符进行搜索

时间:2013-10-01 02:51:12

标签: java collections wildcard

我有HashMap<Integer,String>。我尝试了以下代码来查询Map并返回所有可能的值

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;
}

如果地图有"test","best","crest","zest","testy","tether","temper","teat","tempest"。对te*t的查询应返回"teat","tempest","test"。对于'test *',它应该返回“test”,“testy”。怎么实现呢?是否有任何通配符搜索字符串?我不能使用任何外部库。

2 个答案:

答案 0 :(得分:6)

String queryStr="te*t";

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

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

完整计划

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;
    }
}

答案 1 :(得分:1)

匹配器\w*仅搜索以下字符:[a-zA-Z_0-9]
如果您想使用*匹配器搜索所有字符,那么您应该尝试这样:

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