Java Regex Create toRegExFormat(String pattern)

Here you can find the source of toRegExFormat(String pattern)

Description

Converts wildcard format ('*' and '?') to reg-ex format.

License

Open Source License

Declaration

private static String toRegExFormat(String pattern) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2008 Pierre-Antoine Gr?goire.
 * 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 ava  2s.c o  m*/
 *    Pierre-Antoine Gr?goire - initial API and implementation
 *******************************************************************************/

public class Main {
    /**
     * Converts wildcard format ('*' and '?') to reg-ex format.
     */
    private static String toRegExFormat(String pattern) {
        StringBuffer regex = new StringBuffer(pattern.length());
        boolean escaped = false;
        boolean quoting = false;
        for (int i = 0; i < pattern.length(); i++) {
            char c = pattern.charAt(i);
            if (c == '*' && !escaped) {
                if (quoting) {
                    regex.append("\\E");
                    quoting = false;
                }
                regex.append(".*");
                escaped = false;
                continue;
            } else if (c == '?' && !escaped) {
                if (quoting) {
                    regex.append("\\E");
                    quoting = false;
                }
                regex.append(".");
                escaped = false;
                continue;
            } else if (c == '\\' && !escaped) {
                escaped = true;
                continue;
            } else if (c == '\\' && escaped) {
                escaped = false;
                if (quoting) {
                    regex.append("\\E");
                    quoting = false;
                }
                regex.append("\\\\");
                continue;
            }
            if (!quoting) {
                regex.append("\\Q");
                quoting = true;
            }
            if (escaped && c != '*' && c != '?' && c != '\\') {
                regex.append('\\');
            }
            regex.append(c);
            escaped = c == '\\';
        }
        if (quoting) {
            regex.append("\\E");
        }
        return regex.toString();
    }
}

Related

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