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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19107165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 14:08:49  来源:igfitidea点击:

Search with wildcard in a Collection of String

javacollectionswildcard

提问by NEO

I have a HashMap<Integer,String>. I tried the following code to query the Map and return all possible values

我有一个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;
}

If map has "test","best","crest","zest","testy","tether","temper","teat","tempest". A query of te*tshould 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"。对于“test*”,它应该返回“test”、“testy”。如何实施?是否有任何通配符搜索字符串?而且我不能使用任何外部库。

采纳答案by Prabhakaran Ramaswamy

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

回答by Stefan Finkenzeller

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("\*", ".*");