【问题标题】:Search with wildcard in a Collection of String在字符串集合中使用通配符搜索
【发布时间】:2013-10-01 02:51:12
【问题描述】:

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

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”。如何实施?是否有任何通配符搜索字符串?而且我不能使用任何外部库。

【问题讨论】:

  • String 有方法matches。您还可以使用PatternMatcher 类。
  • 如果列表为空,为什么返回 null?只返回一个空列表会更有意义。
  • assertArrayEquals(new Object[] {"best","crest","tempest","test","zest"}, getSortedArray(dict.query("*est") ));没有返回任何东西。
  • @arshajii 它是测试用例的要求。我无法更改它们。

标签: java collections wildcard


【解决方案1】:
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;
    }
}

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-13
      • 1970-01-01
      相关资源
      最近更新 更多