org.shaf.core.util.PatternUtils.java Source code

Java tutorial

Introduction

Here is the source code for org.shaf.core.util.PatternUtils.java

Source

/**
 * Copyright 2014-2015 SHAF-WORK
 * 
 * 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 org.shaf.core.util;

import java.util.regex.Pattern;

import com.google.common.base.Strings;

/**
 * Utility function for URI operations.
 * 
 * @author Mykola Galushka
 */
public class PatternUtils {

    public static final Pattern getWildCardPattern(final String wildcard) {
        if (Strings.isNullOrEmpty(wildcard)) {
            throw new IllegalArgumentException("The wildcard is not defined.");
        }

        StringBuilder regexp = new StringBuilder();
        for (int i = 0, is = wildcard.length(); i < is; i++) {
            char c = wildcard.charAt(i);
            switch (c) {
            case '*':
                regexp.append(".*");
                break;
            case '?':
                regexp.append('.');
                break;
            case '(':
            case ')':
            case '[':
            case ']':
            case '$':
            case '^':
            case '.':
            case '{':
            case '}':
            case '|':
            case '\\':
                regexp.append('\\');
                regexp.append(c);
                break;
            default:
                regexp.append(c);
                break;
            }
        }
        return Pattern.compile(regexp.toString());
    }
}