Returning a list of wildcard matches from a HashMap in java

前端 未结 3 730
不思量自难忘°
不思量自难忘° 2021-01-04 14:25

I have a Hashmap which may contain wildcards (*) in the String.

For instance,

HashMap students_;

can have

3条回答
  •  感动是毒
    2021-01-04 14:41

    You can use regex to match, but you must first turn "John*" into the regex equivalent "John.*", although you can do that on-the-fly.

    Here's some code that will work:

    String name = "John Smith"; // For example
    Map students_ = new HashMap();
    
    for (Map.Entry entry : students_.entrySet()) {
        // If the entry key is "John*", this code will match if name = "John Smith"
        if (name.matches("^.*" + entry.getKey().replace("*", ".*") + ".*$")) {
            // do something with the matching map entry
            System.out.println("Student " + entry.getValue() + " matched " + entry.getKey());
        }
    }
    

提交回复
热议问题