Search with wildcard in a Collection of String

15,437

Solution 1

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

Solution 2

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("\\*", ".*");
Share:
15,437
NEO
Author by

NEO

Updated on June 04, 2022

Comments

  • NEO
    NEO almost 2 years

    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.