
io.devbench.uibuilder.data.collectionds.utils.LikeExpressionToRegexp Maven / Gradle / Ivy
/*
*
* Copyright © 2018 Webvalto Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.devbench.uibuilder.data.collectionds.utils;
import java.util.regex.Pattern;
public class LikeExpressionToRegexp {
private static final String REGEXP_SPECIAL = "[](){}.*+?$^|#\\";
private static final String REGEXP_MULTIPLE = ".*?";
private static final String REGEXP_SINGLE = ".";
private static final String REGEXP_ESCAPE = "\\";
private static final String LIKE_MULTIPLE = "%";
private static final String LIKE_SINGLE = "_";
public static boolean like(String str, String expr) {
if (str == null || expr == null) {
return false;
}
return Pattern.compile(translateString(expr), Pattern.DOTALL).matcher(str).matches();
}
public static boolean ilike(String str, String expr) {
if (str == null || expr == null) {
return false;
}
return Pattern.compile(translateString(expr), Pattern.CASE_INSENSITIVE | Pattern.DOTALL).matcher(str).matches();
}
public static String translateString(String expression) {
StringBuilder sb = new StringBuilder(expression.length() * 2);
for (char element : expression.toCharArray()) {
translateChar(sb, element);
}
return sb.toString();
}
private static void translateChar(StringBuilder sb, char element) {
if (charIn(element, REGEXP_SPECIAL)) {
sb.append(REGEXP_ESCAPE);
sb.append(element);
} else if (charIn(element, LIKE_SINGLE)) {
sb.append(REGEXP_SINGLE);
} else if (charIn(element, LIKE_MULTIPLE)) {
sb.append(REGEXP_MULTIPLE);
} else {
sb.append(element);
}
}
public static boolean charIn(char c, String s) {
return s.indexOf(c) != -1;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy