Java Regex Create toRegexPattern(String filter)

Here you can find the source of toRegexPattern(String filter)

Description

Convert filter to a regular expression

License

Open Source License

Parameter

Parameter Description

Declaration

public static String toRegexPattern(String filter) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2013 Actuate Corporation.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors://from  w w w. j av  a  2 s .  c o m
 *  Actuate Corporation  - initial API and implementation
 *******************************************************************************/

public class Main {
    /**
     * Convert <code>filter</code> to a regular expression
     * @param filter: ? for any char; * for any string
     * @return
     */
    public static String toRegexPattern(String filter) {
        StringBuffer pattern = new StringBuffer(".*"); //$NON-NLS-1$
        boolean isWaitingForEndQuote = false;
        for (int i = 0; i < filter.length(); i++) {
            char c = filter.charAt(i);
            if (c == '*' || c == '?') {
                if (isWaitingForEndQuote) {
                    pattern.append("\\E"); //$NON-NLS-1$
                    isWaitingForEndQuote = false;
                }
                String s = c == '*' ? ".*" : "."; //$NON-NLS-1$ //$NON-NLS-2$
                pattern.append(s);
            } else {
                if (!isWaitingForEndQuote) {
                    pattern.append("\\Q"); //$NON-NLS-1$
                    isWaitingForEndQuote = true;
                }
                pattern.append(c);
            }
        }
        if (isWaitingForEndQuote) {
            pattern.append("\\E"); //$NON-NLS-1$
        }
        return pattern.append(".*").toString(); //$NON-NLS-1$
    }
}

Related

  1. toRegEx(String input)
  2. toRegex(String name)
  3. toRegex(String param)
  4. toRegex(String wildcard)
  5. toRegExFormat(String pattern)
  6. toRegexPattern(String pattern)