How to implement a SQL like 'LIKE' operator in java?

后端 未结 15 1393
你的背包
你的背包 2020-11-29 03:12

I need a comparator in java which has the same semantics as the sql \'like\' operator. For example:

myComparator.like(\"digital\",\"%ital%\");
myComparator.l         


        
相关标签:
15条回答
  • 2020-11-29 04:07

    .* will match any characters in regular expressions

    I think the java syntax would be

    "digital".matches(".*ital.*");
    

    And for the single character match just use a single dot.

    "digital".matches(".*gi.a.*");
    

    And to match an actual dot, escape it as slash dot

    \.
    
    0 讨论(0)
  • 2020-11-29 04:09

    Regular expressions are the most versatile. However, some LIKE functions can be formed without regular expressions. e.g.

    String text = "digital";
    text.startsWith("dig"); // like "dig%"
    text.endsWith("tal"); // like "%tal"
    text.contains("gita"); // like "%gita%"
    
    0 讨论(0)
  • 2020-11-29 04:11
    public static boolean like(String toBeCompare, String by){
        if(by != null){
            if(toBeCompare != null){
                if(by.startsWith("%") && by.endsWith("%")){
                    int index = toBeCompare.toLowerCase().indexOf(by.replace("%", "").toLowerCase());
                    if(index < 0){
                        return false;
                    } else {
                        return true;
                    }
                } else if(by.startsWith("%")){
                    return toBeCompare.endsWith(by.replace("%", ""));
                } else if(by.endsWith("%")){
                    return toBeCompare.startsWith(by.replace("%", ""));
                } else {
                    return toBeCompare.equals(by.replace("%", ""));
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
    

    may be help you

    0 讨论(0)
提交回复
热议问题